数据库和java连接(eclipse)向users表中增加一条记录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38224607/article/details/80263558
package cn.itcast.ch10.demo;


import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


/*
 * 向users表中增加一条记录
 */
public class Exqmple02 {


public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
//1. 加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//数据库的url
String url = "jdbc:mysql://localhost:3306/ch10";
//数据库用户名
String user = "root";
//数据库密码
String password = "111";
//2. 获取数据库连接对象
conn = DriverManager.getConnection(url, user, password);
String sql = "insert into users(name,password,birthday) values(?,?,?)";
//3. 获取预编译语句对象
pstmt = conn.prepareStatement(sql);
//4. 给各个占位符赋值
pstmt.setString(1,"郑七");
pstmt.setString(2, "abc");
pstmt.setDate(3, Date.valueOf("1998-05-18"));
//5.执行sql语句,返回值是影响记录的行数
int n = pstmt.executeUpdate();
if(n>0){
System.out.println("插入记录成功");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//6.释放资源
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pstmt = null;
}

if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
}



}


}

猜你喜欢

转载自blog.csdn.net/qq_38224607/article/details/80263558