Java connection MySQL Tutorial data code
Package jxc;
Import java.sql.connection;
Import Java.sql.drivermanager;
Import java.sql.preparedstatement;
Import java.sql.ResultSet;
Import java.sql.sqlexception;
Import java.sql.statement;
Import java.sql.*;
public class Jdbcconn {
static connection con;
Static statement stmt;
public static PreparedStatement PS Tutorial T;
static ResultSet rs = null;
public static void load ()/load-driven methods
{
& nbsp; try {
string driver = " Com.mysql.jdbc.driver ";
Class.forName (driver);
} catch (Exception e) {
System.out.println ("No driver Found");
}
}
public static void Conn ()//method of establishing a connection
{
& nbsp; try {
string url = jdbc:mysql:// LOCALHOST:3306/JXC_DB?USEUNICODE=TRUE&CHARACTERENCODING=GBK ";
String user = "root";
String password = "Xiajun";
con = drivermanager.getconnection (URL, user , password);
} catch (Exception ee) {
System.out.println ("Error: no connection");
}
}
public static void Exesql ()//method of executing SQL
{
try {
stmt = Con.createstatement ();
Pst= (PreparedStatement) con.createstatement ();
Stmt.executequery ("");
Stmt.executeupdate ("");
catch (Exception e) {
}
}
public static void Close ()//closed method
{
& nbsp; try {
con.close ();
//Stmt.close ();
pst.close ();
//Rs.close ();
} catch (SqlException ee) {
& nbsp }
}
public static void Close1 () {
try {
Con.close ();
Stmt.close ();
Pst.close ();
Rs.close ();
catch (SqlException ee) {
}
}
}
/*
To load the driver:
1. First find the name of the driver class you want to use: such as Com.mysql.jdbc.driver. You can import using command-line arguments, and you can use the Modify Classpath method, preferably by using the way you import a jar package.
2. Registration driver: There are several ways:
1. Setting the Jdbc.drivers property in the way of command-line arguments
2. Method call Set System Properties: System.setproperty ("Jdbc.drivers", driver); Driver = "Com.mysql.jdbc.driver"
3. Load Driver class: Class.forName (Driver);
4. Using the property file
Step 2. Open database Tutorial connect to MySQL
To establish a connection:
Connection conn = drivermanager.getconnection (URL, username, pwd); URL: The specified data source, "Jdbc:mysql://localhost/test"
Step 3, Execute SQL command
1. Create the Statement object (to use the connection MySQL database in the previous step conn):
Statement st = Conn.createstatement (); 2. Use this object to execute a statement:
St.executequery ("SELECT * from Test"); Executeupdate (); Note that the select query must use ExecuteQuery ();