1、Statement
public class JdbcTest {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://ip:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "密码";
// 1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2、连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
// 3、向数据库发送sql
Statement statement = connection.createStatement();
// 4、编写sql
// String sql = "select * from users";
// String sql = "delete from users where id = 2";
String sql = "INSERT INTO users VALUES (7, '王进', '123', '5623234@qq.com', '1999-2-7');";
// 5、执行sql
// ResultSet resultSet = statement.executeQuery(sql);
// while (resultSet.next()) {
// System.out.println("id=" + resultSet.getObject("id"));
// System.out.println("name=" + resultSet.getObject("name"));
// System.out.println("password=" + resultSet.getObject("password"));
// System.out.println("email=" + resultSet.getObject("email"));
// System.out.println("birthday=" + resultSet.getObject("birthday"));
// }
int i = statement.executeUpdate(sql);
// 返回受影响的行数
System.out.println(i);
// 6、关闭连接
// resultSet.close();
statement.close();
connection.close();
}
}
2、PreparedStatement(预编译)
public class JdbcTest2 {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://ip:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "密码";
// 1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2、连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
// 3、编写sql
String sql = "insert into users(id, name, password, email, birthday) values (?, ?, ?, ?, ?)";
// 4、预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 赋值
preparedStatement.setInt(1, 8);
preparedStatement.setString(2, "狂神");
preparedStatement.setString(3, "123");
preparedStatement.setString(4, "543657@qq.com");
preparedStatement.setDate(5, new Date(new java.util.Date().getTime()));
// 5、执行sql
int i = preparedStatement.executeUpdate();
System.out.println(i);
// 6、关闭连接
preparedStatement.close();
connection.close();
}
}