使用JDBC连接MySQL数据库
import java.sql.*;
public class test1 {
//JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test1";//test1为库的名称
//数据库的用户名与密码
static final String USER = "root";
static final String PASS = "";
public static void main(String args[]) {
Connection conn = null;
Statement stmt = null;
try {
//注册JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
//打开链接
System.out.println("打开数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql = "select id,name,url from websites";
ResultSet re = stmt.executeQuery(sql);
//展开结果集数据库
while(re.next()) {
// 通过字段检索
int id = re.getInt("id");
String name = re.getString("name");
String url = re.getString("url");
//输出数据
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + name);
System.out.print(", 站点 URL: " + url);
System.out.print("\n");
}
//完成后关闭
re.close();//关闭记录集
stmt.close();//关闭声明
conn.close();//关闭连接对象
}catch(SQLException se) {//处理JDBC错误
se.printStackTrace();
}catch(Exception e) {//处理Class.forName错误
e.printStackTrace();
}finally {
//关闭资源
try {//关闭声明
if(stmt != null) {
stmt.close();
}
}catch(SQLException se2) {
}
try {//关闭连接对象
if(conn != null) {
conn.close();
}
}catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("GoodBye!");
}
}