使用Connection对象创建Statement对象
Statement createStatement() 创建一条 sql 语句对象
Statement接口 | 描述 |
---|---|
int executeUpdate(String sql) | DML语句,增删改,insert,update,delete。DDL操作 |
ResultSet executeQuery(String sql) | DQL语句,查询操作,select |
需要将按顺序释放ResultSet,Statement和Connection对象,最好放在finally块中。
ResultSet接口 | 描述 |
---|---|
boolean next() | 游标向下一动一行,默认游标是在表头,所以需要先移动一行 |
getXxx(int or string) | Xxx代表的是不同类型,参数可以是列数(从1开始),也可以是列名 |
Java与sql类型对照
sql 类型 | Jdbc 对应方法 | 返回类型 |
---|---|---|
BIT(1) bit(n) | getBoolean() | boolean |
tinyint | getByte() | byte |
SMALLINT | getShort() | short |
INT | getInt() | int |
BIGINT | getLong() | long |
CHAR,VARCHAR | getString() | String |
Text(Clob) Blob | getClob getBlob() | Clob Blob |
DATE | getDate() | java.sql.Date 只代表日期 |
TIME | getTime() | java.sql.Time 只表示时间 |
TIMESTAMP | getTimestamp() | java.sql.Timestamp 同时有日期和时间 |
示例:
DDL
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres");
statement = conn.createStatement();
statement.executeUpdate("create table student (id int PRIMARY key auto_increment, " + "name varchar(20) not null)");
DML
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres");
Statement stmt = conn.createStatement();
String sql1 = "update account set score = 112 where id = 1";
int count1 = stmt.executeUpdate(sql1);
statement.close();
connection.close();
DQL
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres");
Statement stmt = conn.createStatement();
String sql4 = "select * from account";
ResultSet res1 = stmt.executeQuery(sql4);
res1.next();
String name1 = res1.getString("NAME");