Operating system: Windows 10 64-bit
Java Development environment: MyEclipse
Database: SQL Server 2012
JDBC Driver Package
Download Sqljdbc4.jar
Import into Project
Java code
1 PackageCom.cl.util;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 Importjava.sql.PreparedStatement;6 ImportJava.sql.ResultSet;7 Importjava.sql.SQLException;8 9 Public classDbutil {Ten One //Connection Driver A Private Static FinalString DRIVER = "Com.microsoft.sqlserver.jdbc.SQLServerDriver"; - //Connection Path - Private Static FinalString URL = "Jdbc:sqlserver://localhost:1433;databasename=master"; the //User name - Private Static FinalString USERNAME = "sa"; - //Password - Private Static FinalString PASSWORD = "123"; + - //Static code block + Static { A Try { at //Load Driver - Class.forName (DRIVER); -}Catch(ClassNotFoundException e) { - e.printstacktrace (); -SYSTEM.OUT.PRINTLN ("Database connection exception"); - } in } - to /* + * Get database connection - */ the Public StaticConnection Getconn () { *Connection conn =NULL; $ Try{ Panax Notoginsengconn=drivermanager.getconnection (URL, USERNAME, PASSWORD); -}Catch(SQLException e) { the E.printstacktrace (); + } A returnConn; the } + - /* $ * Close database connection, note the order of closing $ */ - Public voidClose (ResultSet rs, PreparedStatement PS, Connection conn) { - if(rs!=NULL){ the Try{ - Rs.close (); Wuyirs=NULL; the}Catch(SQLException e) { - E.printstacktrace (); Wu } - } About if(ps!=NULL){ $ Try{ - Ps.close (); -ps=NULL; -}Catch(SQLException e) { A E.printstacktrace (); + } the } - if(conn!=NULL){ $ Try{ the Conn.close (); theconn=NULL; the}Catch(SQLException e) { the E.printstacktrace (); - } in } the } the}
Attention
localhost:1433
1433 is the default port number for SQL Server and can be modified on its own by special circumstances
Some security guards may prompt for power-up and disable SQL services.
Remember to open
Locate SQL Server (MSSQLSERVER), start the service
Java connection to SQL Server database