mirror of
https://github.com/wahyd4/wahyd4.github.com.git
synced 2026-08-10 05:47:00 +10:00
- 308 posts reverse-extracted from wahyd4.github.com (Hexo 6.3.0 + NexT 8.25) - Hexo project with NexT theme, reading-experience custom styles - publish-post.sh: write post -> hexo build -> PR (master untouched)
52 lines
1.6 KiB
Markdown
52 lines
1.6 KiB
Markdown
---
|
|
title: "一个Java JDBC连接简单实例"
|
|
date: 2010-11-20 00:00:00
|
|
tags: [java, JDBC]
|
|
---
|
|
|
|
今天在学习java JDBC,这里写了一个简单的java 连接Mysql 数据库的实例供大家参考。此代码代码可以运行。
|
|
|
|
需要注意的是如果你在Eclipse 或者 My Eclipse 里面运行这个代码,你需要下载mysql 数据库的JDBC驱动程序,下载在mysql 官方网站下载即可。并将包里面的mysql-connector-java-5.1.1-bin.jar加入到build path 里面即可(注:这个5.1.1是我下载的connector 版本号,你们的可能不一样。)
|
|
|
|
下面就是代码
|
|
|
|
Java语言:
|
|
|
|
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();
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
}
|