importjava.sql.*;publicclass data {Connection con;ResultSet res;PreparedStatement sql;publicdata(){try{//加载驱动Class.forName("com.mysql.jdbc.Driver");System.out.println("数据库驱动加载成功");//连接数据库
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase","用户名","密码");System.out.println("数据库连接成功");}catch(ClassNotFoundException e){
e.printStackTrace();}catch(SQLException throwables){
throwables.printStackTrace();}}/*数据库操作*///插入语句publicvoidinsert(String user,String password){try{//预处理语句this.sql =this.con.prepareStatement("insert into user value(?,?)");this.sql.setString(1,user);this.sql.setString(2,password);this.sql.executeUpdate();}catch(SQLException throwables){
throwables.printStackTrace();}}//查询语句publicStringselect(String user){String password=null;try{this.sql =this.con.prepareStatement("select password from user where username=?");this.sql.setString(1,user);
sql.setString(1,user);
res=sql.executeQuery();//从预处理的地方查找,查到则返回,否则返回nullwhile(res.next()){
password=res.getString("password");return password;}}catch(SQLException throwables){
throwables.printStackTrace();}returnnull;}publicstaticvoidmain(String[] args){
data data =newdata();String z=data.select("003");System.out.println(z);}}