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

Source: Internet
Author: User
Tags log4j

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. 1. Load the JDBC driver:
  2. Before connecting to the database, first load the driver of the database you want to connect to the JVM (Java Virtual machine),
  3. This is achieved through the static method forname (String className) of the Java.lang.Class class.
  4. After a successful load, an instance of the driver class is registered in the DriverManager class.
  5. 2. Provide the URL of the JDBC connection
  6. • The connection URL defines the protocol, sub-protocol, and data source identity when the database is connected.
  7. • Written form: protocol: Sub-Protocol: Data source identification
  8. Protocol: Always start with JDBC in JDBC
  9. Sub-Protocol: A bridge-connected driver or database management system name.
  10. Data source identification: The tag locates the address of the database source and the connection port.
  11. 3. Create a connection to the database
  12. • To connect to a database, you need to request and obtain a connection object from Java.sql.DriverManager.
  13. The object represents a connection to a database.
  14. • Use DriverManager's getconnectin (string URL, string username,
  15. String password) method to pass in the path to the specified database to be connected, the user name of the database, and
  16. Password to get it.
  17. 4. Create a statement
  18. • To execute an SQL statement, you must obtain an java.sql.Statement instance that is divided into the following 3 statement instances
  19. Type of:
  20. 1. Execute static SQL statements.     Typically implemented through statement instances.
  21. 2. Execute dynamic SQL statements.     Typically implemented through PreparedStatement instances.
  22. 3. Execute the database stored procedure.     Typically implemented through CallableStatement instances.
  23. The specific implementation method:
  24. Statement stmt = Con.createstatement ();
  25. PreparedStatement pstmt = con.preparestatement (sql);
  26. CallableStatement cstmt = Con.preparecall ("{Call Demosp (?,?)}");
  27. 5. Execute SQL statements
  28. The statement interface provides three ways to execute SQL statements: ExecuteQuery, executeupdate
  29. and execute
  30. 1, ResultSet executeQuery (): Execute SQL statement to query database
  31. A result set (ResultSet) object is returned.
  32. 2,int executeupdate (): Used to perform INSERT, update, or
  33. Delete statements and SQL DDL statements, such as CREATE table and drop table
  34. 3. Execute (): Used to perform a return of multiple result sets, multiple update counts, or a combination of the two
  35. Statement.
  36. Specific implementation code:
  37. ResultSet rs = Pstmt.executequery ();
  38. int rows = Pstmt.executeupdate ();
  39. Boolean flag = Pstmt.execute ();
  40. 6. Processing results
  41. Two cases:
  42. 1. The number of records affected by this operation is returned by performing the update.
  43. 2. The result of executing the query returned is a ResultSet object.
  44. resultset contains all rows that conform to the conditions in the SQL statement, and it provides a set of get methods for these
  45. Access to the data in the row.
  46. • Get data using the access method of the result set (ResultSet) object:
  47. While (Rs.next ()) {
  48. String name = rs.getstring ("name");
  49. String pass = rs.getstring (1);
  50. }
  51. 7. Close the JDBC Object
  52. All JDBC objects used are closed after the operation is complete to release the JDBC resource, turn off order harmony
  53. The opposite of the Ming Order:
  54. 1. Close record set
  55. 2. Closing the statement
  56. 3. Close the Connection object

JDBC Connect SQL Server database code:

[Java]View Plaincopyprint?
    1. Package COM.ACCP.JDBC;
    2. Import java.sql.Connection;
    3. Import Java.sql.DriverManager;
    4. Import java.sql.PreparedStatement;
    5. Import Java.sql.ResultSet;
    6. Import java.sql.SQLException;
    7. Import Org.apache.log4j.Logger;
    8. Public class Basedao {
    9. //Use log4j to log logs
    10. private static Logger Logger = Logger.getlogger (Basedao.   Class);
    11. //Connection driver
    12. private static final String DRIVER = "Com.microsoft.sqlserver.jdbc.SQLServerDriver";
    13. //connection path
    14. private static final String URL = "Jdbc:sqlserver://localhost:1433;databasename=myschool";
    15. //user name
    16. private static final String USERNAME = "sa";
    17. //Password
    18. private static final String PASSWORD = "sa";
    19. //Static code block
    20. Static {
    21. try {
    22. //Load driver
    23. Class.forName (DRIVER);
    24. } catch (ClassNotFoundException e) {
    25. E.printstacktrace ();
    26. }
    27. }
    28. /* 
    29. * Get database connection
    30. */
    31. Public Connection getconnection () {
    32. Connection conn = null;
    33. Logger.debug ("Start Connection Database");
    34. try{
    35. Conn=drivermanager.getconnection (URL, USERNAME, PASSWORD);
    36. }catch (SQLException e) {
    37. E.printstacktrace ();
    38. Logger.error ("Database connection failed!  ");
    39. }
    40. Logger.debug ("database connection succeeded");
    41. return conn;
    42. }
    43. /* 
    44. * Close database connection, note the order of closing
    45. */
    46. public void Close (ResultSet rs, PreparedStatement PS, Connection conn) {
    47. if (rs!=null) {
    48. try{
    49. Rs.close ();
    50. rs=null;
    51. }catch (SQLException e) {
    52. E.printstacktrace ();
    53. Logger.error ("shutdown resultset failed");
    54. }
    55. }
    56. if (ps!=null) {
    57. try{
    58. Ps.close ();
    59. ps=null;
    60. }catch (SQLException e) {
    61. E.printstacktrace ();
    62. Logger.error ("shutdown PreparedStatement failed");
    63. }
    64. }
    65. if (conn!=null) {
    66. try{
    67. Conn.close ();
    68. conn=null;
    69. }catch (SQLException e) {
    70. E.printstacktrace ();
    71. Logger.error ("Shutdown Connection failed");
    72. }
    73. }
    74. }
    75. }

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

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.