import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQL {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getCon() {
Connection con=null;
try {
con=(Connection)DriverManager.getConnection( "jdbc:MySQL://localhost:3306/tongxunludb?useUnicode=true&characterEncoding=UTF8" ,"root","123456");
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
System.out.println(getCon());
}
}
连接成功
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQL {
static {
try {
Class.forName("com.mysql.jdbc.Driver");//加载驱动
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getCon() {
Connection con=null;//创建实例
try {
con=(Connection)DriverManager.getConnection( "jdbc:MySQL://localhost:3306/tongxunludb?useUnicode=true&characterEncoding=UTF8" ,"root","123456");//连接数据库
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
Connection con=getCon();
try {
Statement stmt=con.createStatement();//创建statement实例
ResultSet rs=stmt.executeQuery("show tables");//创建结果集实例
while(rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();//关闭结果集
stmt.close();//关闭statement实例
} catch ( SQLException e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
con.close();//关闭数据库连接
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
读取正确