Java calls MySQL instance:
Package com.tanglei.test1;
Import java.sql.*;
public class testsql{
public static void Main (String []args) {
MySQL mysql=new MySQL ();
}
}
Class mysql{
MySQL jdbc url writing method: jdbc:mysql://host Name: The name of the connection port/database? parameter = value
Avoid Chinese garbled to specify Useunicode and characterencoding
To create a database on a database management system before performing a database operation, the name will be
The following statement is preceded by the creation of the Javademo database
Connection Cnn=null;
String SQL;
String url= "Jdbc:mysql://localhost:3306/test?usessl=false";
Public Mysql () {
try{
The reason to use the following statement is because you want to use the MySQL driver, so we have to drive it up,
It can be loaded through class.forname, or it can be driven by initialization.
1. Adding drivers
Class.forName ("Com.mysql.jdbc.Driver");
2. Establish a connection
A connection represents a database connection
Cnn=drivermanager.getconnection (URL, "Tester", "pass1234");
Cnn.setautocommit (FALSE);
3. Create statement
Statement contains many methods, such as executeupdate can be inserted, update and delete, etc.
Statement stmt=cnn.createstatement ();
Sql= "CREATE table if not EXISTS student (no varchar (), Name varchar (), primary key (No))";
int res=stmt.executeupdate (SQL);
Cnn.commit ();
System.out.println (res);
if (res!=-1) {
SYSTEM.OUT.PRINTLN ("Database creation succeeded! ");
Sql= "INSERT into student (No,name) VALUES (' S001 ', ' Ray ')";
Stmt.executeupdate (SQL);
Sql= "INSERT into student (No,name) VALUES (' S002 ', ' swead ')";
Stmt.executeupdate (SQL);
Sql= "INSERT into student (No,name) VALUES (' S003 ', ' Deny ')";
Stmt.executeupdate (SQL);
Sql= "SELECT * from student";
ResultSet rs=stmt.executequery (SQL);
System.out.println ("School number \ t name");
while (Rs.next ()) {
System.out.println (rs.getstring (1) + "\ T" +rs.getstring (2));
}
sql= "drop table student";
Stmt.executeupdate (SQL);
}
}catch (Exception e) {
E.printstacktrace ();
try{
Cnn.rollback ();
}catch (SQLException E1) {
E1.printstacktrace ();
}
}finally{
try{
Cnn.close ();
}catch (SQLException e) {
E.printstacktrace ();
}
}
}
}
This article from the "8141167" blog, reproduced please contact the author!
Java calls to MySQL instance