Recently in the teacher layout of SQL Server large job, one of the problems is to use Java to connect to SQL Server. The previous connection database was completed in MyEclipse. This time I'll switch to Notepad. Here's my step:
1. First, download the Java-connected SQL Server driver:sqljdbc
2. After decompression, find the location of Sqljdbc.jar, mine is: D:\Program Files (x86) \sqljdbc\sqldriver\sqldriver
3. Configure environment variables: Add Sqljdbc.jar file Locations in the classpath of the system, and note that the previous classpath is separated by semicolons . For example mine is:
Something;d:\program Files (x86) \sqljdbc\sqldriver\sqldriver\sqljdbc.jar
Finally click OK, the environment variable configuration is complete, next is the configuration SQL Server. The steps are as follows:
1. Open SQL Server Configuration Manager and locate the SQLEXPRESS protocol in the network configuration. Open the TCP/IP protocol .:
2. Right-click the TCP/IP protocol and select Properties to modify the TCP dynamic port in the IP address Ipall to: 1433.:
3. After clicking OK, restart the SQL Server service in the SQL Server surface Area configuration.
This time, we have configured the environment variables and SQL Server, the next is the implementation of Java code, I chose to use Notepad to connect the database, so the JDK environment variables also need to be configured, about its environment variable configuration, you can click here . Here's the Java code:
1 Importjava.sql.Connection;2 ImportJava.sql.DriverManager;3 4 Public classDbconnect {5 6 //driver name7 PrivateString Driver = "Com.microsoft.sqlserver.jdbc.SQLServerDriver";8 9 //URL points to the name of the database to be accessedTen PrivateString url = "Jdbc:sqlserver://localhost;database=zhouxy"; One A //user name and password when logging into SQL Server - PrivateString user = "Zhouxy"; - PrivateString Password = "123"; the - Public voidGetConnect () { - Try { - //Load Driver + Class.forName (driver); - + //connecting to a database AConnection conn =drivermanager.getconnection (Url,user,password); at - if(!conn.isclosed ()) { -System.out.println ("Database is connected successful!"); - } -}Catch(Exception e) { - e.printstacktrace (); in } - } to + Public Static voidMain (string[] args) { -Dbconnect DBC =NewDbconnect (); the Dbc.getconnect (); * } $}
Then, compile and run the above code on the command line, when the output
Database is connected successful!
That's a success! :