/**
* 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