Java 数据库连接
public class JDBCUtils { public static Connection getConn(){ Connection conn=null; //不是局部 {Class.forName("com.mysql.jdbc.Driver");//注册驱动 {...}点出try catch String url="jdbc:mysql://localhost:3306/market0929?useUnicode=true&characterEncoding=UTF-8"; String username="root"; String password="";// 空 //点 add catch↓ conn=DriverManager.getConnection(url, username, password); } return conn; }
public static Connection getConn(){//JDBC从文件读取信息
Connection conn=null; //不是局部 Properties pro=new Properties(); try{ FileInputStream fis=new FileInputStream("src/pro.properties"); pro.load(fis); //相对路径 正斜杠 Class.forName(pro.getProperty("driverClass"));//点出try catch String url=pro.getProperty("url"); String username=pro.getProperty("username"); String password=pro.getProperty("password");//空//点 add catch↓ conn=DriverManager.getConnection(url, username, password); } catch (Exception e) {throw RuntimeException("数据库连接失败")} return conn; } src/pro.properties文件://无空格 密码空串(空格) 保存 driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/guanjiapo?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull username=root password=
//释放增删改资源 public static void close(Connection conn, PreparedStatement pst){ if(pst!=null){pst.close(); //点出try catch} if(conn!=null){conn.close(); //点出try catch} } //释放查询资源 public static void close(Connection conn,PreparedStatement pst,ResultSet rs){ if(rs!=null){rs.close(); //点出try catch} if(pst!=null){pst.close(); //点出try catch} if(conn!=null){conn.close(); //点出try catch} } } public int xxxSort(String sname,String sdesc) throws SQLException{ //(Sort sort)//传入对象 对象.getXxx() //ArrayList<Sort>// 返回查询集合 Connection conn=JDBCUtils.getConn(); //获取链接 String sql="insert into sort(sid,sdesc) values(?,?)"; //新增 //String sql="delete from sort where sid=?"; //删除 //String sql="update sort set sname=?,sdesc=? where sid=?"; //修改 //String sql="Select * from sort where sid=?"; //查询 //String sql="select count(*) from user where uname=? and pwd=?"; PreparedStatement pst=conn.prepareStatement(sql);//语执行对象 pst.setInt(1,sid); //设置替代符的值 pst.setString(2,sdesc); //pst.setString(2,sort.getSdesc()); int row=pst.executeUpdate(); //执行增删改语句 1:成功 //ResultSet rs=pst.executeQuery();//执行查询语句 返回结果集合 /*//处理查询结果集 ArrayList<Sort> list=new ArrayList<Sort>(); while(rs.next()){ Sort s=new Sort(); s.setSid(rs.getInt("sid")); s.setSname(rs.getString("sname")); list.add(s); } //int count=0; //查到的记录数 //while(rs.next()){count=rs.getInt(1);}*/ JDBCUtils.close(conn, pst); //增删改 释放资源 //JDBCUtils.close(conn, pst, rs); //查询 释放资源 return row; //return list; }