原⽣jdbc与预处理对象PreparedStatment 2

API详解

注册驱动:

DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 不建议使⽤,原因有2个:

  • 导致驱动被注册2次
  • 强烈依赖数据库的驱动jar

解决办法:

  • Class.forName("com.mysql.jdbc.Driver");

API详解:获得链接

static Connection getConnection(String url, String user, String password) :试图建⽴到给定数据库 URL 的连接。
参数说明:

  • url 需要连接数据库的位置(⽹址)
  • user⽤户名
  • password 密码

例如: getConnection("jdbc:mysql://localhost:3306/test_wensong", "root", "root");

了解:

URL: SUN公司与数据库⼚商之间的⼀种协议。

jdbc:mysql://localhost:3306/test_wensong


协议⼦协议 IP :端⼝号数据库
mysql数据库: jdbc:mysql://localhost:3306/test_wensong 或者 jdbc:mysql:///test_wensong(默认本机连接)
oracle数据库: jdbc:oracle:thin:@localhost:1521:sid

API详解:java.sql.Connection接⼝:⼀个连接
接口的实现在数据库驱动中。所有与数据库交互都是基于连接对象的。

  • Statement createStatement(); //创建操作sql语句的对象

API详解:java.sql.Statement接⼝: 操作sql语句,并返回相应结果

String sql = "某SQL语句";
获取Statement语句执⾏平台:Statement stmt =con.createStatement();

常⽤⽅法:

  • int executeUpdate(String sql); --执⾏insert update delete语句.
  • ResultSet executeQuery(String sql); --执⾏select语句.
  • boolean execute(String sql); --仅当执⾏select并且有结果时才返回true,执⾏其他的语句返回false.

API详解:处理结果集(注:执行insert、update、delete无需处理)

ResultSet实际上就是⼀张⼆维的表格,我们可以调⽤其boolean next() ⽅法指向某⾏记录,当第⼀次调⽤next() ⽅法时,便指向第⼀⾏记录的位置,这时就可以使⽤ResultSet提供的getXXX(int col) ⽅法来获取指定列的数据:(与数组索引从0开始不同,这⾥索引从1开始)

rs.next();//指向第⼀⾏
rs.getInt(1);//获取第⼀⾏第⼀列的数据

常⽤⽅法:

  • Object getObject(int index) / Object getObject(String name) 获得任意对象
  • String getString(int index) / String getString(String name) 获得字符串
  • int getInt(int index) / int getInt(String name) 获得整形
  • double getDouble(int index) / double getDouble(String name) 获得双精度浮点型

API详解:释放资源

与IO流⼀样,使⽤后的东⻄都需要关闭!关闭的顺序是先得到的后关闭,后得到的先关闭。

rs.close();
stmt.close();
con.close();

猜你喜欢

转载自blog.csdn.net/weixin_40959890/article/details/107746106