JDBC练习第14天-Insert语句
需求:向数据表中添加一条数据:
代码如下:
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/*
* account表 添加一条记录Insert语句
*
* */
public class JdbcDemo02 {
public static void main(String[] args) throws Exception{
Connection conn = null;
Statement stmt = null;
try {
//1.导入mysql-connector-java.jar包,注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.定义sql
//String sql = "insert into account value(null,'王五',3000)";
String sql = "insert into account value(null,'李四',3000)";
//3.获取Connection对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db01","root","admin");
//4.获取执行sql的对象Statement
stmt = conn.createStatement();
//5.执行sql
int count = stmt.executeUpdate(sql);
//6.处理结果
System.out.println(count);
if(count>0){
System.out.println("添加成功!");
}else{
System.out.println("添加失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
//stmt.close();
//7.释放资源
//避免空指针异常
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
添加成功:
数据库表更新: