美文网首页
JDBC讲解

JDBC讲解

作者: 顾念0703 | 来源:发表于2019-04-11 15:52 被阅读0次

    1.JDBC API:Java DataBase Connectivity(java数据库访问技术)
    a.Connection conn=DriverManager.getConnection(url,"root","passwod")         //修通道 建立连接
    b.PreparedStatement ps=conn.preparsedStatement(sql)        //货车 语句
        eg,I.sql = "select *from student whrer sname=?";
    c.ResultSet rs=ps.executeQuery();        //显示结果

    新建Web项目、包、类。写入驱动的三个方法。
    Connection conn=null;
    PerpareStatement ps=null;
    ResultSet rs=null;
    String sql="SELECT * FROM book1";
    String url="jdbc:mysql://localhost:3306/demo";

    conn=DriverManager.getConnection(url,"user","password");
    ps = conn.prepareStatment(sql);
    rs = ps.executeQuery();         //执行查询

    while(rs.next()){
            String sno=rs.getString(1);
            System.out.println(sno);
            System.out.println(re.getString(1));
            System.out.println(re.getString(2));
            System.out.println(re.getString(3));
            System.out.println(re.getString(4));
            System.out.println(re.getInt(5));
    }
            rs.close();
            ps.close();
            conn.close();
    开始时倒入jar包:Class.Class.forName("com.mysql.Drive");
    调整异常:close之前全部包裹进一个异常
    close相关的接在其后的finally里。


    下面附上实测代码:
    package jdbc;

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import javax.servlet.jsp.jstl.sql.Result;

    public class JDBC {

    public static void main(String[] args) {

    TODO Auto-generated method stub

    Connection conn = null;

    PreparedStatement ps = null;

    ResultSet rs = null;

    String url = jdbcmysqllocalhost3306bookstor;  数据库位置  直接跟数据库名称

    String sql = SELECT  FROM student;  SQL语句

    try {  加载驱动的异常

    Class.forName(com.mysql.jdbc.Driver);

    conn = DriverManager.getConnection(url, root, 123456);

    ps = conn.prepareStatement(sql);

    rs = ps.executeQuery();  获得数据

    while (rs.next()) {

    System.out.println(rs.getString(1));

    System.out.println(rs.getString(2));

    System.out.println(rs.getString(3));

    System.out.println(rs.getString(4));

    System.out.println(rs.getInt(5));

    }

    } catch (ClassNotFoundException e) {

    TODO Auto-generated catch block

    e.printStackTrace();

    } catch (SQLException e) {

    TODO Auto-generated catch block

    e.printStackTrace();

    } finally {

    try {

    rs.close();

    ps.close();

    conn.close();

    } catch (SQLException e) {

    TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

    }

    }

    相关文章

      网友评论

          本文标题:JDBC讲解

          本文链接:https://www.haomeiwen.com/subject/thutwqtx.html