Related software and drivers:
MySQL Download version: 4.1.11
Http://dev.mysql.com/downloads/mysql/4.1.html
JDBC Driver download version: 3.1.8
Http://dev.mysql.com/downloads/connector/j/3.1.html
Copy Code code as follows:
Code
Code highlighting produced by Actipro Codehighlighter (freeware) Http://www.CodeHighlighter.com/-->import java.sql.*;
public class MySQL {
public static String URL = "Jdbc:mysql://localhost:3306/test";//characterencoding=gbk
public static String username = "root";
public static String password = "root";
public static Connection con;
public static Statement stmt;
public static ResultSet RS;
public static void Main (string[] args) throws SQLException {
Connect ();
Operation ();
Stmt.close ();
Con.close ();
}
public static void Test () {
String sql_select = "SELECT * FROM TableName where id=1";
String Sql_insert = "INSERT INTO TableName (Col1,col2 ...) VALUES (' 1 ', ' 2 ' ...) ";
String sql_update = "UPDATE tablename set colname= ' Update ' where id=1";
Insert (Sql_insert);
Select (Sql_select);
Update (sql_update);
}
public static void Connect () {
Positioning drive
try {
Class.forName ("Com.mysql.jdbc.Driver");
SYSTEM.OUT.PRINTLN ("Load driven success!");
catch (ClassNotFoundException e) {
SYSTEM.OUT.PRINTLN ("Load driver failed!");
E.printstacktrace ();
}
Establish a connection
try {
con = drivermanager.getconnection (URL, username, password);
stmt = Con.createstatement ();
SYSTEM.OUT.PRINTLN ("Database connection successful!");
catch (SQLException e) {
SYSTEM.OUT.PRINTLN ("Database connection failed!");
}
}
public static void Select (String sql) {
try {
rs = stmt.executequery (SQL);
ResultSetMetaData meta_data = Rs.getmetadata ();//Column name
for (int i_col = 1; i_col <= meta_data.getcolumncount (); i_col++) {
System.out.print (Meta_data.getcolumnlabel (i_col) + "");
}
System.out.println ();
while (Rs.next ()) {
for (int i_col = 1; i_col <= meta_data.getcolumncount (); i_col++) {
System.out.print (rs.getstring (i_col) + "");
}
System.out.println ();
}
Rs.close ();
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Data query failed!");
}
}
public static void Insert (String sql) {
try {
Stmt.clearbatch ();
Stmt.addbatch (SQL);
Stmt.executebatch ();
SYSTEM.OUT.PRINTLN ("Data insert success!");
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Data insertion failed!");
}
}
public static void update (String sql) {
try {
Stmt.executeupdate (SQL);
SYSTEM.OUT.PRINTLN ("Data Update successful!");
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Data update failed!");
}
}
}