One of the methods of database connection in JAVA

Source: Internet
Author: User

/**
* Database Connection Class
*
*/

Package com.cn.MysqlConnect;

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;

public class Test {

/**
* @param args
*/
public static void Main (string[] args) {

Database connection steps:
1 Adding the Connect jar package
2 Writing connection strings and driver names
3 Writing the driver name:
String Server = "Com.mysql.jdbc.Driver";
Writing a link string
String url = "Jdbc:mysql://localhost:3306/myschool";
3 Load Driver
Connection Connection = null; Database Connection Object
PreparedStatement preparedstatement = null;
ResultSet ResultSet = null;

try {
The content executed here runs out of the local virtual machine environment, and the database may be faulted to the local disk, and the JDK cannot catch the exception
Class.forName (server); Java inside exception handling mechanism, must be placed in the try catch inside
Connection = drivermanager.getconnection (URL, "root", "");
SYSTEM.OUT.PRINTLN ("Success Connection Mysqldatabase");
Perform a query table operation
String sql = "SELECT * from student";
PreparedStatement = connection.preparestatement (sql);
ResultSet = Preparedstatement.executequery ();
while (Resultset.next ()) {
System.out.println (Resultset.getint (1) + ""
+ resultset.getstring (2));
}
} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Driver error");
} finally {

Code that executes, regardless of whether the code in the try is wrong, to release resources that the JDK cannot release
try {

Connection.close (); Manually Releasing resources
} catch (Exception ee) {

}

}

}

}

One of the methods for database connections in JAVA

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.