import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.cj.jdbc.Driver;
//向表中添加一条记录
public class JdbcDemo02 {
public static void main(String[] args) throws Throwable {
Statement stmt=null;
Connection conn = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库的连接对象
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/ceshi?serverTimezone=GMT%2B8", "root","123456");
//3.定义sql
String sql= "insert into student values(3,'wangwu',2000)";
//4.获取执行sql的对象
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) {
// TODO Auto-generated catch block
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();
}
}
}
}
}
Jdbc连接数据库入门(2)--向表中添加一条记录
最新推荐文章于 2022-11-15 08:00:00 发布