Two ways to connect SQL server2008 with Java

Source: Internet
Author: User

Recently learned Java Connection Database (SQL Server), found that we have two common methods, then here I summarize how to use the two methods, there are their differences, and we generally use which method.

Method One: Use Jdbc-odbc bridge to connect to SQL Server, as intermediary connection database;

Note that we have to bring in the SQL package every time we connect to the database: import java.sql.*; the next steps are the habitual steps, and I'll enumerate them in terms of the use of each step:

1. Configure the data Source: Open Control Panel, management tools, data Source (ODBC), (typically we use a user DSN) press the Add button->sql server-> write down the name of the data source (you name it, suppose it is test, For the following example), and then write down the server name of the connection (generally default to local), change the default database to (tick the database you want to connect), and then always make sure that the data source configuration is complete.

2. Load driver: Class.fornmae ("Sun.jdbc.odbc.JdbcOdbcDriver");

3. Get Connected: Connection ct=drivermanager.getconnection ("Jdbc:odbc:test"); test is the data source name when configuring the data source

4. Create PreparedStatement (there is no statement, compared to PreparedStatement, it has many drawbacks), this statement is mainly used to send SQL statements to the database.

5. Close all operations at the end of the line,

Import java.sql.*;p Ublic class PreparedStatement {  public static void Main (string[] args) {Connection ct =        Null        PreparedStatement PS = null;                                                                                                                                                                                                        ResultSet Rs=null;                                                                                                                          try {//Load driver Class.forName ("Sun.jdbc.od Bc.            Jdbcodbcdriver ");            Get Connected Ct=drivermanager.getconnection ("Jdbc:odbc:test");            Create a PreparedStatement that relaxes the SQL statement ps=ct.preparestatement ("SELECT * From Product Name table") to the database;            Get results rs=ps.executequery ();//This method is suitable for finding data from a table//If you want to insert, delete, update data to the table, you need to use Method executeupdate ();                while (Rs.next ()) {//here Rs.next () must use the next () method, otherwise there is a null pointer error String number=rs.getstring (1);                String string=rs.getstring (2); System.out.prinTLN (number+ "" +string);                                                                                                                                                                                              }                                                                                                                          } catch (Exception e) {e.printstacktrace ();                    Finally {//closes the resource, remembering the order in which the resources are closed, and closing the resource, based on the inverse order of the assigned value try {if (rs!=null) {                Rs.close ();                } if (PS! = null) ps.close ();            if (ct! = null) ct.close ();            } catch (Exception e) {e.printstacktrace (); }        }    }}

This code has been tested and I'm not going to do it here.

Note: Can we also use? The method of assignment, which is more advantageous to us

Ps=ct.preparestatement ("SELECT * from Product Name table Whrer Product name =? ");

Ps.setstring (1, "mobile phone");//Represents a string that adds "phone" to the first question mark. If it is an integer with the Setint () method;

Method Two: Use the driver to manipulate the database directly

Here spit trough, this method is better than the above method, more use, but the work done more early, in order to achieve this step of operation, I do not know how many tears, here I have encountered difficulties and problems listed to solve.

1. There is a need to introduce a JAR package, here SQL server2008, as long as the introduction of Sqljdbc4.jar package on the line. This package Baidu on the download. Here I mainly provide how to introduce this package.

Method: Toolbar Project Options->properties->java Build Path Select libraries-> Click Add Externar jars button Then select Sqljdbc4.jar in your computer to import.

2. This step requires your SQL Server knowledge, because we connect to the database is generally using SQL authentication, so you need to create your own account password, here I just demonstrate the use of the database in the original user name SA, as illustrated in this example:

Method: First Use Windows authentication to enter the database, and then in the security of the login name to select the system given the user name SA, single-Machine right-click

Select the properties of the button, modify the password here, modify the password you need to click OK. Then disconnect and reconnect with the current user name and password. It is good to create a new database in this user name.

3. Then perform the code demonstration:

Import java.sql.*;p Ublic class JDBC1 {/** * @param args */public static void main (string[] args) {        TODO auto-generated method stub Connection ct = null;        PreparedStatement PS = null;        ResultSet rs = null;            try {//First step, load drive Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver");            Get Connected Ct=drivermanager.getconnection ("Jdbc:sqlserver://localhost:1433;databasename=liuyan", "sa", "3209554");                                                       Create PreparedStatement ps=ct.preparestatement ("select * from UserInformation where Name= ' Zhang Sanfeng '");            Rs=ps.executequery ();            This method is useful for finding data from a table//If you want to insert, delete, update data to the table, you need to use the method executeupdate ();                while (Rs.next ()) {//here Rs.next () must use the next () method, otherwise there is a null pointer error String number=rs.getstring (1);                String string=rs.getstring (2);                String string2=rs.getstring (3); System.out.println(number+ "" +string+ "" +string2);        }} catch (Exception e) {e.printstacktrace ();                }finally{try {if (rs!=null) {rs.close ();                } if (PS! = null) ps.close ();            if (ct! = null) ct.close ();            } catch (Exception e) {e.printstacktrace (); }        }    }}

This is tested and the result is absolutely no problem. Very happy to solve such a problem.

This article is from the "one person's Dream" blog, please be sure to keep this source http://8831691.blog.51cto.com/8821691/1407490

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.