JDBC

数据库连接

      p.load(new FileInputStream(new File("jdbc.properties"));
        //获取驱动名
        String driverName=p.getProperty("driverName");
        String url=p.getProperty("url");
        String  user=p.getProperty("user");
        String password=p.getProperty("password");
         //通过反射获取驱动并加载
        Class.forName( driverName );
        //获取连接Connection
        Connection conn=DriverManager.getConnection(url,user,password);
        System.out.println("数据库连接成功");

SQL语句

查询

String sql="select * from emp where name=?"; //?占位符
PrepareStatement ps=conn.prepareStatement(sql);
//给占位符设值
ps.setString(1,"jack");
//执行SQL语句
ResultSet rs=ps.excuteQuery();
//处理结果集
while(rs.next()){
int id=rs.getInt(1);
String name=rs.getString(2);
String age=rs.getInt(3);
System.out.println("id="+id+",name="+name+",age="+age);

插入

//SQL语句编写
sql="insert into emp values(?,?,?)";
ps=conn.prepareStatement(sql);
ps.setInt(1,1001);
ps.setString(2,"rose");
ps.setInt(3,22);
ps.excuteUpdate();
//关闭
rs.close();
ps.close();
conn.close();







       



     

你可能感兴趣的:(JDBC)