1. Install the JDBC SP3 installation program of MS on the Internet.
2. After the installation is successful, set classpath and add install_dir/lib/msbase. jar; install_dir/lib/msutil. jar; install_dir/lib/MSSQLServer. jar to classpath;
3. After step 2 is completed, you can use the following general code to test whether the database can be connected;
Import java. SQL .*;
Class test {// This program passes the jdk1.4.2 debugging.
Public static void main (string ARGs [])
{
String url = "JDBC: Microsoft: sqlserver: // localhost: 1433; databasename = northwind ";
String user = "sa"; // replace it with your own database username
String Password = "sa"; // replace it with your own Database User Password
String sqlstr = "select customerid, companyName, contactname from customers ";
Try {// The Exception Handling statement here is required. Otherwise, it cannot be compiled!
Class. forname ("com. Microsoft. JDBC. sqlserver. sqlserverdriver ");
System. Out. println ("class instantiation successful! ");
Connection con = drivermanager. getconnection (URL, user, password );
System. Out. println ("the connection image is created successfully! ");
Statement ST = con. createstatement ();
System. Out. println ("statement created successfully! ");
Resultset rs = st.exe cutequery (sqlstr );
System. Out. println ("data table operation successful! ");
System. Out. println ("----------------! ");
While (Rs. Next ())
{
System. Out. Print (Rs. getstring ("customerid") + "");
System. Out. Print (Rs. getstring ("companyName") + "");
System. Out. println (Rs. getstring ("contactname "));
}
Rs. Close ();
St. Close ();
Con. Close ();
}
Catch (exception ERR ){
Err. printstacktrace (system. Out );
}
}
}
If everything passes and the records in the database are displayed on the console, the database connection is successful! Of course, in general, it will not be so smooth if you connect to the database for the first time. Therefore, pay attention to the following:
1. you must carefully check your classpath, so there must be no certain error, for example, put sqlserver. jar writes less R and sqlsever. jar; and so on. this is a common mistake.
2. The database must use the windows and database hybrid identity authentication method.