Detailed steps and code for connecting JDBC to the SQL Server database

Source: Internet
Author: User
  • Follow these steps to connect JDBC to the SQL Server database:
    1. Load the JDBC driver: Before connecting to the database, first load the driver of the database to be connected to the JVM (Java Virtual Machine. lang. class class static method forname (string classname) implementation. After the driver class is loaded, the driver class instance is registered to the drivermanager class. 2. Provide the URL for JDBC connection • the connection URL defines the protocol, sub-protocol, and data source identification for database connection. • Writing format: Protocol: Sub-Protocol: Data Source Identification Protocol: In JDBC, the sub-Protocol always starts with JDBC: the driver of the bridge connection or the name of the database management system. Data source ID: Mark the address and connection port of the database source. 3. Create a database connection • to connect to the database, you must request java. SQL. drivermanager and obtain the connection object. This object represents a database connection. • Use the getconnectin (string URL, string username, string password) method of drivermanager to pass in the path of the database to be connected, and obtain the username and password of the database. 4. To create a statement • to execute an SQL statement, you must obtain a java. SQL. Statement instance. The statement instance can be divided into three types: 1. Execute a static SQL statement. It is usually implemented through a statement instance. 2. Execute dynamic SQL statements. It is usually implemented through the preparedstatement instance. 3. Execute the database stored procedure. It is usually implemented through the callablestatement instance. Specific implementation methods: Statement stmt = con. createstatement (); preparedstatement pstmt = con. preparestatement (SQL); callablestatement cstmt = con. preparecall ("{call demosp (? ,?)} "); 5. Execute the SQL statement interface provides three ways to execute the SQL statement: executequery, executeupdate, and execute 1. resultset executequery (): Execute the SQL statement to query the database, returns a result set 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 (): it is used to execute statements that return multiple result sets, multiple update counts, or a combination of the two. Code for implementation: resultset rs = pstmt.exe cutequery (); int rows = pstmt.exe cuteupdate (); Boolean flag = pstmt.exe cute (); 6. processing result: 1. The number of records affected by this operation is returned when an update is executed. 2. The result returned by executing the query is a resultset object. • Resultset contains all rows that meet the conditions in the SQL statement, and it provides access to the data in these rows through a set of get methods. • Use the access method of the result set object to obtain data: While (RS. next () {string name = Rs. getstring ("name"); string pass = Rs. getstring (1);} 7. After closing the JDBC object operation, you must close all the used JDBC objects to release the JDBC resources. The close sequence is the opposite of the clear sequence: 1. Close record set 2. Close Declaration 3. Close connection object

    JDBCCode for connecting to the SQL Server database:

    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 record Private Static logger = logger. getlogger (basedao. class); // connection driver Private Static final string driver = "com. microsoft. sqlserver. JDBC. sqlserverdriver "; // connection path priva Te static final string url = "JDBC: sqlserver: // localhost: 1433; databasename = myschool"; // username Private Static final string username = "sa "; // password Private Static final string Password = "sa"; // static code block static {try {// load the driver class. forname (driver);} catch (classnotfoundexception e) {e. printstacktrace () ;}}/** get database connection */public connection getconnection () {connection conn = NULL; logger. debug ("start connecting to Database"); try {conn = dri Vermanager. getconnection (URL, username, password);} catch (sqlexception e) {e. printstacktrace (); logger. Error ("database connection failed! ");} Logger. debug ("database connection succeeded"); Return conn;}/** close database connection, pay attention to 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 ("failed to disable resultset") ;}} if (PS! = NULL) {try {ps. close (); PS = NULL;} catch (sqlexception e) {e. printstacktrace (); logger. error ("failed to disable preparedstatement") ;}} if (Conn! = NULL) {try {Conn. close (); Conn = NULL;} catch (sqlexception e) {e. printstacktrace (); logger. error ("failed to close connection ");}}}}

  • 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.