Detailed steps and code for JDBC connection to a SQL Server database

Source: Internet
Author: User
Tags log4j

The steps for JDBC to connect to a SQL Server database are as follows:

 1. Load the JDBC driver (only once): Before connecting to the database, first load the driver of the database you want to connect to the JVM (Java Virtual machine), which is forname by the static method of the Java.lang.Class class (String className   Achieve    After a successful load, an instance of the driver class is registered in the DriverManager class.       2. The URL connection URL that provides the JDBC connection defines the protocol, sub-protocol, and data source identity when the database is connected.       • Written form: protocol: Sub-Protocol: Data source identity protocol: Always start the sub-protocol with JDBC in JDBC: The driver for the bridge connection or the name of the database management system.      Data source identification: The tag locates the address of the database source and the connection port.       3. Create a connection to the database (Connection) • To connect to a database, you need to request and obtain a Connection object from the Java.sql.DriverManager that 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 and password of the database to Get. 4, create a statement to execute the SQL statement, you must obtain an Java.sql.Statement instance, statement instances are divided into the following 3 types: 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 concrete realization way: Statement stmt = Con.createstatement ();          PreparedStatement pstmt = con.preparestatement (sql);   CallableStatement cstmt = Con.preparecall ("{Call Demosp (?,?)}"); 5. Execute SQL statement The statement interface provides three ways to execute SQL statements: ExecuteQuery, Executeupdate, and execute 1, ResultSet executeQuery (): Perform a check        Queries the SQL statement of the database and returns a result set (ResultSet) object. 2, int executeupdate (): Used to execute INSERT, UPDATE or DELETE statements, and SQL DDL statements, such as: CREATE Table and drop table 3, execute (): Used to perform a return      A statement that returns multiple result sets, multiple update counts, or a combination of the two.             The specific implementation of the code: ResultSet rs = Pstmt.executequery ();             int rows = Pstmt.executeupdate ();    Boolean flag = Pstmt.execute ();        6, processing results in two cases: 1, the implementation of the update returned is the number of records affected by this operation.       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 access to the data in those rows through a set of Get methods.            • 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 objectAfter the operation is complete, all the JDBC objects used are closed to release the JDBC resource, closing order and declaration order opposite: 1, closing recordset 2, closing Declaration 3, closing the Connection object
Note: You must not forget to close the JDBC object
     数据库连接(Connection)是非常稀有的资源,用完后必须马上释放,      如果Connection不能及时正确的关闭将导致系统宕机。    Connection的使用原则是尽量晚创建,尽量早的释放。


JDBC Connect SQL Server database code:

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 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 Statics {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 the 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 ("Close resultset failed");}} if (ps!=null) {try{ps.close ();p s=null;} catch (SQLException e) {e.printstacktrace (); Logger.error ("Close PreparedStatement failed");}} if (conn!=null) {try{conn.close (); conn=null;} catch (SQLException e) {e.printstacktrace (); Logger.error ("Close connection Failed");}}}

Reprint Address: http://blog.csdn.net/qy1387/article/details/7944133

Very like the author of the first paragraph of the JDBC connection of the detailed explanation, before it will be used, but not very clear specific principles, lack of theoretical explanations, thank you!!

Detailed steps and code for JDBC connection to a SQL Server database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.