写一个简单的数据库连接类
package com.landingbj.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private Connection conn;
public Connection getConnecton(){
try {
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名world
String url = "jdbc:mysql://127.0.0.1:3306/test";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "dir13652";
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public void closeConn(){
try {
if(this.conn!=null){
this.conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
编写一个测试数据库连接类
package com.landingbj.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestConnection {
public static void main(String[] args) throws ClassNotFoundException {
DBConnection db = new DBConnection();
Connection conn = db.getConnecton();
String name;
try {
if (conn != null) {
System.out.println("数据库已经连接成功");
// statement用来执行SQL语句
Statement statement = conn.createStatement();
// 要执行的SQL语句
String sql = "select * from students";
// 结果集
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
// 选择Name这列数据
name = rs.getString("name");
// 输出结果
System.out.println(rs.getString("age") + "\t" + name);
}
}
conn.close();
db.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
}
}