java中链接数据库用的是jdbc这个第三方库 首先从各个官网 比如MySQL上下载mysql类型的jdbc包 随后导入到java项目的lib目录下,随后config buildPath 来加载这个包
随后就可以在项目中使用这个第三方库了
首先加载数据库的驱动 数据库的驱动名称为
public static final String names = "com.mysql.jdbc.Driver";
苏后创建connection这个类 来链接数据库
Connection conn = null;
Statement sta = null;
加载数据库的驱动
try {
Class.forName(names);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
response.sendRedirect(request.getContextPath() + "/index.jsp");
System.out.println("error1");
}
链接数据库
String jdbcPath = "jdbc:mysql://localhost:3306/Demo";
String user = "root";
String pass = "";
try {
conn = DriverManager.getConnection(jdbcPath,user,pass);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
随后创建Statement这个类 这个类就是用来执行sql语句的
sta = conn.createStatement();
String selectSql = "select password from user where id = " + "\"" + userName + "\"";
System.out.println(1);
ResultSet res = sta.executeQuery(selectSql);
System.out.print(selectSql);
执行后的结果集放在ResultSet这个类中,这个永远不会反悔null值 要判断是否存在值,通过res.next来判断即可
随后进行数据的取出
if(res.next()){
String sqlPassword = res.getString(1);
这样即可,总体来说只要会了这个jdbc的使用 还是比较简单的