A complete example of connecting Java to the SQL Server database

Source: Internet
Author: User

Package com. gamvan. Conn;
Import java. SQL. connection;
Import java. SQL. drivermanager;
Import java. SQL. preparedstatement;
Import java. SQL. resultset;
Import java. SQL. statement;

Public class conntest {
Private string gvdriver = "";
Private string gvuser = "sa"; // database access user
Private string gvpassword = "123"; // Database Access Password
Private Static string message = "congratulations, the database connection is normal! ";
Public connection getconnection (){
Connection conn = NULL;
Try {
Class. forname ("net. SourceForge. jtds. JDBC. Driver ");
/**
* The database driver jtds needs to download the jtds jar package and place it in the lib directory of the software runtime environment.
* Db_test indicates the database name.
*/
Gvdriver = "JDBC: jtds: sqlserver: // 127.0.0.1: 1433; databasename = db_test ";
Conn = drivermanager. getconnection (gvdriver, gvuser, gvpassword );
} Catch (exception e ){
Conn = NULL;
Message = E. tostring ();
}
Return conn;
}

/**
* Set the closing method.
*/
Public void close (connection c ){
Try {
If (C! = NULL) C. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}

/* Test database connection */
Public static void main (string ARGs []) {

Conntest Ct = new conntest ();

Connection con = CT. getconnection ();

// Print information
System. Out. println (Message );

// Good habits should be developed. Remember to close the database connection when it is used up
Ct. Close (CON );
}

}

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.