Detailed steps and code for JDBC to connect to a SQL Server database
The steps for JDBC to connect to a SQL Server database are as follows:
[Java]View Plaincopyprint?
- 1. Load the JDBC driver:
- Before connecting to the database, first load the driver of the database you want to connect to the JVM (Java Virtual machine),
- This is achieved through the static method forname (String className) of the Java.lang.Class class.
- After a successful load, an instance of the driver class is registered in the DriverManager class.
- 2. Provide the URL of the JDBC connection
- • The connection URL defines the protocol, sub-protocol, and data source identity when the database is connected.
- • Written form: protocol: Sub-Protocol: Data source identification
- Protocol: Always start with JDBC in JDBC
- Sub-Protocol: A bridge-connected driver or database management system name.
- Data source identification: The tag locates the address of the database source and the connection port.
- 3. Create a connection to the database
- • To connect to a database, you need to request and obtain a connection object from Java.sql.DriverManager.
- The object represents a connection to a database.
- • Use DriverManager's getconnectin (string URL, string username,
- String password) method to pass in the path to the specified database to be connected, the user name of the database, and
- Password to get it.
- 4. Create a statement
- • To execute an SQL statement, you must obtain an java.sql.Statement instance that is divided into the following 3 statement instances
- Type of:
- 1. Execute static SQL statements. Typically implemented through statement instances.
- 2. Execute dynamic SQL statements. Typically implemented through PreparedStatement instances.
- 3. Execute the database stored procedure. Typically implemented through CallableStatement instances.
- The specific implementation method:
- Statement stmt = Con.createstatement ();
- PreparedStatement pstmt = con.preparestatement (sql);
- CallableStatement cstmt = Con.preparecall ("{Call Demosp (?,?)}");
- 5. Execute SQL statements
- The statement interface provides three ways to execute SQL statements: ExecuteQuery, executeupdate
- and execute
- 1, ResultSet executeQuery (): Execute SQL statement to query database
- A result set (ResultSet) object is returned.
- 2,int executeupdate (): Used to perform INSERT, update, or
- Delete statements and SQL DDL statements, such as CREATE table and drop table
- 3. Execute (): Used to perform a return of multiple result sets, multiple update counts, or a combination of the two
- Statement.
- Specific implementation code:
- ResultSet rs = Pstmt.executequery ();
- int rows = Pstmt.executeupdate ();
- Boolean flag = Pstmt.execute ();
- 6. Processing results
- Two cases:
- 1. The number of records affected by this operation is returned by performing the update.
- 2. The result of executing the query returned is a ResultSet object.
- resultset contains all rows that conform to the conditions in the SQL statement, and it provides a set of get methods for these
- Access to the data in the row.
- • Get data using the access method of the result set (ResultSet) object:
- While (Rs.next ()) {
- String name = rs.getstring ("name");
- String pass = rs.getstring (1);
- }
- 7. Close the JDBC Object
- All JDBC objects used are closed after the operation is complete to release the JDBC resource, turn off order harmony
- The opposite of the Ming Order:
- 1. Close record set
- 2. Closing the statement
- 3. Close the Connection object
JDBC Connect SQL Server database code:
[Java]View Plaincopyprint?
- Package COM.ACCP.JDBC;
- Import java.sql.Connection;
- Import Java.sql.DriverManager;
- Import java.sql.PreparedStatement;
- Import Java.sql.ResultSet;
- Import java.sql.SQLException;
- Import Org.apache.log4j.Logger;
- Public class Basedao {
- //Use log4j to log logs
- private static Logger Logger = Logger.getlogger (Basedao. Class);
- //Connection driver
- private static final String DRIVER = "Com.microsoft.sqlserver.jdbc.SQLServerDriver";
- //connection path
- private static final String URL = "Jdbc:sqlserver://localhost:1433;databasename=myschool";
- //user name
- private static final String USERNAME = "sa";
- //Password
- private static final String PASSWORD = "sa";
- //Static code block
- Static {
- try {
- //Load driver
- Class.forName (DRIVER);
- } catch (ClassNotFoundException e) {
- E.printstacktrace ();
- }
- }
- /*
- * Get database connection
- */
- Public Connection getconnection () {
- Connection conn = null;
- Logger.debug ("Start Connection Database");
- try{
- Conn=drivermanager.getconnection (URL, USERNAME, PASSWORD);
- }catch (SQLException e) {
- E.printstacktrace ();
- Logger.error ("Database connection failed! ");
- }
- Logger.debug ("database connection succeeded");
- return conn;
- }
- /*
- * Close database connection, note the order of closing
- */
- public void Close (ResultSet rs, PreparedStatement PS, Connection conn) {
- if (rs!=null) {
- try{
- Rs.close ();
- rs=null;
- }catch (SQLException e) {
- E.printstacktrace ();
- Logger.error ("shutdown resultset failed");
- }
- }
- if (ps!=null) {
- try{
- Ps.close ();
- ps=null;
- }catch (SQLException e) {
- E.printstacktrace ();
- Logger.error ("shutdown PreparedStatement failed");
- }
- }
- if (conn!=null) {
- try{
- Conn.close ();
- conn=null;
- }catch (SQLException e) {
- E.printstacktrace ();
- Logger.error ("Shutdown Connection failed");
- }
- }
- }
- }
Detailed steps and code for JDBC to connect to a SQL Server database