实现数据库与项目的链接

来源:互联网 发布:高端 商务礼品 知乎 编辑:程序博客网 时间:2024/05/22 15:46
String driver = "com.mysql.jdbc.Driver";
//服务器路径与数据库名
String url = "jdbc:mysql://127.0.0.1:3306/classs";
//操作数据库的用户
String user = "root";
//数据库密码
String password = " ";
//加载驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
//获取链接
Connection conn = null;
try {
conn = (Connection) DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
//创建处理对象
Statement statement = null;
try {
statement = (Statement) conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
//编写sql语句
String sql = "select * from user where person_number='830682000102238';";
//执行sql语句
ResultSet res=null;
try {
res = statement.executeQuery(sql);
while(res.next()){
//输出数据表里字段为id的字段名
System.out.print(res.getString("id"));
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
res.close();
//关闭操作
statement.close();
conn.close();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}

1 0
原创粉丝点击