JDBC程序(数据库查询)
步骤:
-
加载驱动 -
连接数据库DriverManager -
获得执行sql的对象 Statement -
获得返回的结果集 ResultSet -
释放连接
DriverManager
Class.forName("com.mysql.cj.jdbc.Driver");
URL
String url="jdbc:mysql://localhost:3306/bjpowernode?
useUnicode=true&characterEncoding=utf8&useSSL=true";
Statement 执行SQL的对象 PrepareStatement执行SQL的对象
Statement statement=connection.createStatement();
String sql="SELECT * from dept";
statement.executeQuery();
statement.execute();
statement.executeLargeUpdate();
ResultSet 查询的结果集,封装了所有的查询结果
获得指定的数据类型
reultSet.getObject();
resultSet.getString();
resultSet.getInt();
resultSet.getFloat();
遍历,指针
resultSet.afterLast();
resultSet.beforeFirst();
resultSet.next();
resultSet.previous();
resultSet.absolute(row);
释放资源
resultSet.close();
statement.close();
connection.close();
整体代码
package com.pp.lesson01;
import java.net.ConnectException;
import java.sql.*;
public class jdbcfirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=utf8&usrSSL=true";
String name="root";
String password="111111";
Connection connection= DriverManager.getConnection(url,name,password);
Statement statement=connection.createStatement();
String sql="SELECT * from dept";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("DEPTNO="+resultSet.getObject("DEPTNO"));
System.out.println("DNAME="+resultSet.getObject("DNAME"));
System.out.println("LOC="+resultSet.getObject("LOC"));
}
resultSet.close();
statement.close();
connection.close();
}
}
|