Reference: http://weistar.iteye.com/blog/1744871
Preparatory work:
1. Download the JDBC Driver package: http://www.microsoft.com/zh-cn/download/details.aspx?id=21599
2. When the download is complete, click Run and you will be prompted to select the Unzip directory.
3. After the decompression is complete, enter < You extract to the directory >\sqljdbc_3.0\chs, there are Sqljdbc.jar and Sqljdbc4.jar, here use Sqljdbc4.jar
4. Configure the SQL Server2008 port:
a.sqlserver2008 port is dynamic, find SQL Server2008 Configuration Manager
B.sql Server Network Configuration->mssqlserver protocol->TCP/IP
C. If TCP/IP is off, start it, right-click Properties, and configure the following:
D.sql Server service->sql server (MSSQLSERVER), right click-restart
Connection work:
1. Primer work:
Right-click the Java project you created, find build path, choose Add External Archives, Find the package you want to import Sqljdbc4.jar, click Open can be introduced, after the introduction of the project under the Referencedelibraries can display this package.
2. Write code tests:
Importjava.sql.Connection; ImportJava.sql.DriverManager; ImportJava.sql.ResultSet; Importjava.sql.Statement; Public classsqlserver{ Public Static voidMain (String args[])
{ String Urlserver= "jdbc:sqlserver://127.0.0.1:1433;databasename=test;user=sa;password=sa123";//sqlserverIdentity ConnectionString urlwindows= "jdbc:sqlserver://127.0.0.1:1433;databasename=test;integratedsecurity=true;";//Windows Integrated Mode connection//declares the JDBC objects. Connection con =NULL; Statement stmt=NULL; ResultSet RS=NULL; Try
{ //Establish a connectionSystem.out.println ("Ready to connect!!! "); Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); Con=drivermanager.getconnection (Urlserver); System.out.println ("Successful connection!!!" "); //write an SQL statement and execute the return dataString SQL = "SELECT * from a"; stmt=con.createstatement (); RS=stmt.executequery (SQL); //Display the data while(Rs.next ())
{System.out.println (rs.getstring (2)); } } Catch(Exception e)
{E.printstacktrace (); } finally
{ if(rs! =NULL) Try
{Rs.close (); }
Catch(Exception e)
{ } if(stmt! =NULL) Try
{Stmt.close (); }
Catch(Exception e)
{ } if(Con! =NULL) try
{con.close (); }
Catch(Exception e)
{ } } } }
Java Connection SQL Server2008