How to configure DataSource in Java to connect to MS SQL Server?

I am trying to follow the Java JDBC tutorials to write a Java program that can connect to SQL Server 2008. I am lost in creating a connection.

The following snippet from the tutorial:

InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");
Connection con = ds.getConnection(); 

There is no explanation what comp / env / jdbc / myDB should refer to, and I don't know how to choose a port. In addition, the ds object is apparently defined twice.

I use a driver JSQLDataSourcefor recording. Can someone point me in the right direction?

http://java.sun.com/docs/books/tutorial/jdbc/basics/connecting.html

+3
source share
5 answers

JDBC Microsoft,

:

String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");

, , . SQL- - 1433.

: . JDBC Microsoft, JTDS. .

JNDI- Java EE, . , , , .

Java EE , . , DriverManager .

: , Sun DataSource, , . , , DataSource " ". , .

, , , . "ds".

"... lookup", , "... ", .

+8

, - .

.

, SQLServerDataSource - :

    SQLServerDataSource dataSource = new SQLServerDataSource();
    dataSource.setUser("aUser");
    dataSource.setPassword("password");
    dataSource.setServerName("hostname");
    dataSource.setDatabaseName("db");

dataSource.getConnection();

, .

connection.prepareStatement("some sql with ? substitutions");

- sql :

connection.prepareCall

.

+11

jTDS SQL Server.

URL- :

jdbc:jtds:sqlserver://localhost/Finance;instance=sqlexpress

URL- jTDS.

, jtds SQL-.

+4

This question has long been answered. A question was asked about finding JNDI. When searching, you should see the application server log to see what the connection is tied to. For example, when I start Jboss, I see:

[ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=myDB' to JNDI name 'java:myDB'

Now this is the key. That’s how I should look for a search -

InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:myDB");

Notice how the server log and code point to the JNDI name java: myDB .

0
source
DataSource ds = new SimpleDriverDataSource(new com.mysql.jdbc.Driver(),
    "jdbc:mysql://database:1433;databaseName=name", "username", "password");
JdbcTemplate jdbc = new JdbcTemplate(ds);
0
source

Source: https://habr.com/ru/post/1711829/


All Articles