准备工作
在阅读本页之前,请执行以下操作:
select empno,ename from emp;
// 'db' is an open database connection
rows, err := db.Query("select empno,ename from emp")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
fmt.Println("Initial balances:")
for rows.Next() {
var id, balance int
if err := rows.Scan(&id, &balance); err != nil {
log.Fatal(err)
}
fmt.Printf("%d %d\n", id, balance)
}
try (Connection connection = ds.getConnection()) {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select empno,ename from emp");
while (rs.next()) {
int id = rs.getInt(1);
int bal = rs.getInt(2);
System.out.printf("ID: %10s\nBalance: %5s\n", id, bal);
}
rs.close();
} catch (SQLException e) {
System.out.printf("sql state = [%s]\ncause = [%s]\nmessage = [%s]\n",
e.getSQLState(), e.getCause(), e.getMessage());
}
with conn.cursor() as cur:
cur.execute("select empno,ename from emp")
rows = cur.fetchall()
for row in rows:
print([str(cell) for cell in row])
要对查询结果进行排序,请使用ORDER BY
子句。
例如:
select * from emp order by empno;
要限制查询的结果,请使用LIMIT子句。
例如:
select * from emp order limit 5;
有关参考文档和更多示例,请参阅LIMIT/OFFSET语法页面。
具有双向连接的选择查询的语法如下所示
SELECT
e.ename, b.dname
FROM
emp AS e
JOIN
dept AS d
ON
e.deptno = d.deptno
WHERE
e.empno is not null
ORDER BY
e.empno
LIMIT
5;