Copy codeThe Code is as follows:
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 driver
Try {
Class. forName ("com. mysql. jdbc. Driver ");
System. out. println ("driver loaded successfully! ");
} Catch (ClassNotFoundException e ){
System. out. println ("failed to load the driver! ");
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.exe cuteQuery (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.exe cuteBatch ();
System. out. println ("data inserted successfully! ");
} Catch (Exception e ){
System. out. println ("data insertion failed! ");
}
}
Public static void update (String SQL ){
Try {
Stmt.exe cuteUpdate (SQL );
System. out. println ("data update successful! ");
} Catch (Exception e ){
System. out. println ("data update failed! ");
}
}
}