首先创建表
然后在web.xml中加入驱动依赖包
mysql mysql-connector-java5.1.49
然后编写测试
1.配置mysql信息
2,加载驱动
3,链接数据库
4.向数据库发送sql的对象Statement
5.编写sql语句
6.执行sql语句
7.关闭资源
//生成主方法快捷键psvm
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
//1加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.链接数据库
Connection connection = DriverManager.getConnection(url,username,password);
//向数据库发送sql的对象statement,CRUD还有PreparedStatement安全的
Statement statement = connection.createStatement();
//4.编写sql语句
//String sql ="select * from jdbc.users;";
String sqld = "delete from users where id =3;";
//5.执行sql语句
//查询,返回一个resultSet结果集,
//ResultSet rs = statement.executeQuery(sql);
//增删改,返回值是受影响的行数
int i = statement.executeUpdate(sqld);
//6.关闭链接释放资源
//先创建的资源最后关闭
//rs.close();
statement.close();
connection.close();
}
}
预编译sql
1.配置mysql信息
2,加载驱动
3,链接数据库
4.编写sql语句
5.向数据库发送sql的对象PreparedStatement
6.执行sql语句
7.关闭资源
public class TestJdbc2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url ="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String root ="root";
String password = "root";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.链接数据库
Connection connection = DriverManager.getConnection(url, root, password);
//3.编写sql语句(预编译)
//使用中文问号发生错误
String sql = "insert into users(id, name, password, email, birthday)values(?,?,?,?,?);";
//4.向数据库发送一个sql的PreparedStatement的对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//给第一个占位符?,赋值为1
preparedStatement.setInt(1,4);
preparedStatement.setString(2,"希尔维嘉学java");
preparedStatement.setString(3,"24567");
preparedStatement.setString(4,"@qqqdad2");
//双重对象第二次需要用java引用
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
//5.执行sql,预编译sql执行语句不用放sql,否则报错
// int i =preparedStatement.executeUpdate(sql);
int i =preparedStatement.executeUpdate();
if (i>0){
System.out.println("插入成功.,.,");
}
preparedStatement.close();
connection.close();
}
}



