7.9 KiB
title, author, comments, excerpt, layout, permalink, categories, tags
| title | author | comments | excerpt | layout | permalink | categories | tags | |||
|---|---|---|---|---|---|---|---|---|---|---|
| 一个Java JDBC连接简单实例 | wahyd4 | true | 今天在学习java JDBC,这里写了一个简单的java 连接Mysql 数据库的实例供大家参考。此代码代码可以运行。 | post | /2010/11/java-jdbc/ |
|
|
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) throws Exception {
String user = “root”;
String pwd = “root”;
String conJDBC = “jdbc:mysql://localhost:3306/jdbc”;// 设置连接JDBC地址
Class.forName(“com.mysql.jdbc.Driver”); // 加载驱动
Connection conn = DriverManager.getConnection(conJDBC, user, pwd);// 创建连接
Statement stmt = conn.createStatement();// 创建执行语句对象
ResultSet res = stmt.executeQuery(“SELECT *FROM stdinfo”);// 执行语句,获取结果
while (res.next()) {
System.out.println(res.getInt(“id”)+“,”+res.getString(“name”)+“,”+res.getInt(“age”));// 输出对象
}
try {
if (res != null) {
res.close(); // 处理异常,关闭 ResultSet 对象
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close(); // 关闭 Connecton 对象
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}