1.需要jar包的支持:
<dependency>
<groupId>MysqL</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
2.非安全型(未使用预编译)
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);
//3.向数据库发送sql的对象Statement
Statement statement = connection.createStatement();
//4.编写sql
String sql = "select * from users";
//5.查询sql
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){
System.out.println("id=" + rs.getobject("id"));
System.out.println("name=" + rs.getobject("name"));
System.out.println("password=" + rs.getobject("password"));
System.out.println("email=" + rs.getobject("email"));
System.out.println("birthday=" + rs.getobject("birthday"));
}
//6.关闭连接,释放资源
rs.close();
statement.close();
connection.close();
}
}
3.预编译型
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 username = "root";
String password = "root";
//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, 4);
preparedStatement.setString(2, "林");
preparedStatement.setString(3, "123456");
preparedStatement.setString(4, "[email protected]");
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
//5.执行sql
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("插入成功");
}
//6.关闭连接,释放资源
preparedStatement.close();
connection.close();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。