package SQL;
import java.sql.*;
public class DBConn {
public static Connection getConnection() throws SQLException,java.lang.ClassNotFoundException {
String driver = "com.mysql.jdbc.Driver"; //驱动名字
String dbName = "mydb1"; //数据库名字
String password = "root"; //数据库登录密码
String userName = "root"; //数据库登录名
String url = "jdbc:mysql://localhost:3306/" + dbName;
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userName, password);
return conn;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Connection conn = getConnection(); //创建连接
String sql = "select * from mydb1.student where id<126";
PreparedStatement ps = conn.prepareStatement(sql); //声明状态
ResultSet rs = ps.executeQuery(); //记录集合
while (rs.next()) {
System.out.println("id : " + rs.getInt(1) + " name : " + rs.getString(2) + " "+" score : " +rs.getString(3));
}
// 关闭记录集
if (rs != null) {
try {
rs.close();
}catch (SQLException e) { e.printStackTrace(); }
}
// 关闭声明
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 关闭链接对象
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}