Java uses jdbc to connect to SQL database instances

Source: Internet
Author: User

<P> import java. SQL. *; </p> <p> public class test {
Public static void main (String [] args ){
String JDriver = "com. microsoft. sqlserver. jdbc. SQLServerDriver"; // SQL Database Engine
String connectDB = "jdbc: sqlserver: // localhost: 1433; DatabaseName = ***"; // Data Source
Try
{
Class. forName (JDriver );
} Catch (ClassNotFoundException e)
{
System. out. println ("failed to load database engine ");
System. exit (0 );
}
System. out. println ("database driver succeeded ");

Try
{
String user = "sa ";
String password = "<a href =" mailto: sy@50.129 "> *** </a> ";
Connection con = DriverManager. getConnection (connectDB, user, password); // connect to the database object
System. out. println ("database connected successfully ");
Statement stmt = con. createStatement (); // create an SQL command object
System. out. println ("start to read data ");
ResultSet rs1_stmt.exe cuteQuery ("SELECT * FROM user_info"); // return the SQL statement query result set (SET)
// Output each record cyclically
While (rs. next ())
{
// Output each field
System. out. println (rs. getString (1) + "\ t" + rs. getString (2) + "\ t" + rs. getString (3 ));
}
System. out. println ("read finished ");

// Close the connection
Stmt. close (); // close the connection to the command object
Con. close (); // close the database connection
}
Catch (SQLException e)
{
E. printStackTrace ();
// System. out. println ("database connection error ");
System. exit (0 );
}
}
} </P>

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.