import java.sql.*;
public class UseDriver {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost/sql_test";
String userName = "root";
String password = "root";
String sql = null;
Connection conn = null;
Statement stmt = null;
try {
//第一步:加载驱动器
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException e) {
System.err.print("ClassNotFoundException");
}
try {
//第二步:调用DriverManager.getConnection静态方法得到数据库连接
System.out.println("@@@@@@");
conn = DriverManager.getConnection(url, userName, password);
System.out.println("@@@@@@");
//创建Statement语句
stmt = conn.createStatement();
sql = "INSERT INTO student " +
"VALUES('12', 'zhangjun', 'tianjin', '1981-01-01')";
//使用Statement语句对象执行SQL语句
stmt.executeUpdate("DELETE FROM student WHERE stu_id='12'");
stmt.executeUpdate(sql);
System.out.println("Insert a row successful!");
} catch(SQLException e) {
System.err.println("Insert SQLException");
} finally {
//关闭语句和数据库连接
try {
stmt.close();
conn.close();
} catch(SQLException e) {
System.err.println("Close SQLException");
}
}
}
}
运行结果:
@@@@@@
Insert SQLException
Exception in thread "main" java.lang.NullPointerException
at UseDriver.main(UseDriver.java:38)
public class UseDriver {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost/sql_test";
String userName = "root";
String password = "root";
String sql = null;
Connection conn = null;
Statement stmt = null;
try {
//第一步:加载驱动器
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException e) {
System.err.print("ClassNotFoundException");
}
try {
//第二步:调用DriverManager.getConnection静态方法得到数据库连接
System.out.println("@@@@@@");
conn = DriverManager.getConnection(url, userName, password);
System.out.println("@@@@@@");
//创建Statement语句
stmt = conn.createStatement();
sql = "INSERT INTO student " +
"VALUES('12', 'zhangjun', 'tianjin', '1981-01-01')";
//使用Statement语句对象执行SQL语句
stmt.executeUpdate("DELETE FROM student WHERE stu_id='12'");
stmt.executeUpdate(sql);
System.out.println("Insert a row successful!");
} catch(SQLException e) {
System.err.println("Insert SQLException");
} finally {
//关闭语句和数据库连接
try {
stmt.close();
conn.close();
} catch(SQLException e) {
System.err.println("Close SQLException");
}
}
}
}
运行结果:
@@@@@@
Insert SQLException
Exception in thread "main" java.lang.NullPointerException
at UseDriver.main(UseDriver.java:38)
改成 e.printStackTrace();看看详细的错误信息
conn = DriverManager.getConnection(url, userName, password);可疑的错误:
1、sql_test 错误
2、password 错误
3、端口不是默认的3306