当前位置:Gxlcms > 数据库问题 > JDBC知识总结

JDBC知识总结

时间:2021-07-01 10:21:17 帮助过:5人阅读

public class JdbcTest { 2 public static void main(String[] args) throws ClassNotFoundException, SQLException { 3 //1.加载驱动 4 Class.forName("com.mysql.jdbc.Driver"); 5 //2.获取与数据库的连接 6 String username="root"; 7 String password="123456"; 8 String url="jdbc:mysql://localhost:3306/jdbcstudy"; 9 Connection connection = DriverManager.getConnection(url, username, password); 10 11 //3.创建向数据库发送sql的statement对象 12 //createStatement():创建向数据库发送sql的statement对象 13 Statement statement = connection.createStatement(); 14 15 String sql="select id,name,password,email from users"; 16 //excuteQuery(String sql):用于向数据发送查询语句 17 //4.向数据库发送sql 18 ResultSet resultSet = statement.executeQuery(sql); 19 20 //ResultSet类讲解:next()方法:移动到下一行 21 //5.取出结果集 22 while(resultSet.next()){ 23 System.out.println(resultSet.getObject("id")); 24 System.out.println(resultSet.getObject("name")); 25 System.out.println(resultSet.getObject("password")); 26 System.out.println(resultSet.getObject("email")); 27 } 28 29 //6.释放资源 30 resultSet.close(); 31 statement.close(); 32 connection.close(); 33 34 35 } 36 }

JDBC中常用类讲解

JDBC中常用类讲解
**DriverManager:**用于加载驱动,并创建与数据库的连接,获得connection接口;
推荐使用 Class.forName(“com.mysql.jdbc.Driver”);
Connection(接口):建立数据库连接的一个接口,主要的常用方法:
createStatement():创建向数据库发送sql的statement对象
prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象
prepareCall(sql):创建执行存储过程的callableStatement对象。
setAutoCommit(boolean autoCommit):设置事务是否自动提交
commit() :在链接上提交事务
rollback() :在此链接上回滚事务

Statement(接口):用于向数据库发送sql语句;常用方法:
executeQuery(String sql) :用于向数据发送查询语句。
executeUpdate(String sql):用于向数据库发送insert、update或delete语句

ResultSet(接口):结果集,statement发送sql语句,得到的结果封装在ResultSet中。

JDBC知识总结

标签:alt   获得   url   username   state   java   base   ring   地址   

人气教程排行