import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Test01_操作步骤 {
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
//获取Statement
stmt = conn.createStatement();
//执行sql语句
String sql = "insert into t_user(username,password,age) values ('aaa','456',22stme);";
int num = stmt.executeUpdate(sql);
//处理这个结果
System.out.println(num);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭数据库资源(注意顺序)
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
首先看你的catch里面输出的错误信息是什么。
无非就是驱动没有找到
数据库无法连上(mysql没有配置对,防火墙没有打开端口,用户名密码)
查询语句错误(比如说字段、表名不对,类型不对,不符合约束等)
String sql = "insert into t_user(username,password,age) values ('aaa','456',22stme);";
这行代码中22stme变量在main方法上面定义的?age是int类型?22stme变量传入的值要跟定义的age类型一致