jdbc学习

加载并注册数据库驱动:在项目里配置数据库驱动,移除也是在这里面移除:右击项目-> Build Path -> Configure Build Path ->libraries -> Add Exteranl JARs


Driver接口:
  数据库的jdbc驱动类名:com.mircrosoft.jdbc.sqlserver.SQLServlerDriver.
             oracle.jdbc.driver.OracleDriver
             com.mysql.jdbc.Driver
  数据库连接:Connection connect(String url, Properties info) throws SQLException


加载与注册JDBC驱动:调用Class类的forName
建立连接到数据库:调用DriverManager类的getConnection,返回一个Connection对象。
        SQL Serve:jdbc:microsoft:sqlserver://localhost:1443;databasename=名字;
        Oracle:jdbc:oracle:thin:@localhost:1521:ORCL
        Mysql:jdbc:mysql://localhost:3306/数据库名字

public class demo2 {
    
    //数据库地址  test_6这个是mysql数据库里的数据库
    private static String dbUrl = "jdbc:mysql://localhost:3306/test_6";

    //用户名
    private static String dbUserName = "root";
    
    //密码
    private static String dbPassword = "lcp8090";
    
    //驱动名称
    private static String jdbcNmae = "com.mysql.jdbc.Driver";
    
    public static void main(String[] args) {
        //加载数据库驱动
     try {
            Class.forName(jdbcNmae);
            System.out.println("加载驱动成功");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("加载驱动失败");
        }
        //创建的新 Connection 对象有一个与之关联的最初为空的类型映射.与特定数据库的连接(会话)。
        Connection con = null;
        
        try{
            //获取数据库连接,引入的是Connection接口
            con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
            System.out.println("数据库连接成功");
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            try {
                //数据库关闭
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

 


访问数据库:
Statement
  调用Connection对象的createStatement()方法创建一个Statement对象,用于向数据库发送SQL语句。
  executeQuery(sql语句),返回一个ResultSet对象,ResultSet对象用于查看执行的结果。
  executeUpdate(sql指定的insert,update,delete语句),更新数据。可以用来创建表。
  execute(sql语句),返回多个结果集或者更新行数。

数据库连接
public class DbUtil {
    // 数据库地址
    private static String dbUrl="jdbc:mysql://localhost:3306/db_book";
    // 用户名
    private static String dbUserName="root";
    // 密码
    private static String dbPassword="123456";
    // 驱动名称
    private static String jdbcName="com.mysql.jdbc.Driver";
    

    public Connection getCon()throws Exception{
        Class.forName(jdbcName);
        Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        return con;
    }
    
    /**
     * 关闭连接
     */
    public void close(Statement stmt,Connection con)throws Exception{
        if(stmt!=null){
            stmt.close();
            if(con!=null){
                con.close();
            }
        }    
    }
}
图书模型:
public class Book {

    private int id;
    private String bookName;
    private float price;
    private String author;
    private int bookTypeId;

    public Book(int id, String bookName, float price, String author,int bookTypeId) {
        super();
        this.id = id;
        this.bookName = bookName;
        this.price = price;
        this.author = author;
        this.bookTypeId = bookTypeId;
    }
    public Book(String bookName, float price, String author, int bookTypeId) {
        super();
        this.bookName = bookName;
        this.price = price;
        this.author = author;
        this.bookTypeId = bookTypeId;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getBookTypeId() {
        return bookTypeId;
    }
    public void setBookTypeId(int bookTypeId) {
        this.bookTypeId = bookTypeId;
    }
}
使用statment 接口实现添加数据操作
1)方法1
public class Demo1 {
    public static void main(String[] args) throws Exception{
        DbUtil dbUtil=new DbUtil();
        String sql="insert into t_book values(null,'java牛逼',888,'B哥',1)";
        Connection con=dbUtil.getCon(); //获取数据连接
        Statement stmt=con.createStatement(); // 获取Statement
        int result=stmt.executeUpdate(sql);
        System.out.println("操作的结果:"+result+"数据");
        stmt.close();  // 关闭statement
        con.close();   // 关闭连接
    }
}
2)方法2
public class Demo2 { private static DbUtil dbUtil=new DbUtil(); private static int addBook2(Book book)throws Exception{ Connection con=dbUtil.getCon(); // 获取连接 String sql="insert into t_book values(null,'"+book.getBookName()+"',"+book.getPrice()+",'"+book.getAuthor()+"',"+book.getBookTypeId()+")"; Statement stmt=con.createStatement(); // 创建Statement int result=stmt.executeUpdate(sql); dbUtil.close(stmt, con); // 关闭Statement和连接 return result; } public static void main(String[] args) throws Exception{ Book book=new Book("Java牛牛2", 1212, "牛哥2", 2); int result=addBook2(book); if(result==1){ System.out.println("添加成功!"); }else{ System.out.println("添加失败!"); } } }
使用statment接口实现更新数据操作

public class Demo1 {

    private static DbUtil dbUtil = new DbUtil();
    private static int updateBook(Book book) throws Exception {
        Connection con = dbUtil.getCon(); // 获取连接
        String sql = "update t_book set bookName='" + book.getBookName()
                + "',price=" + book.getPrice() + ",author='" + book.getAuthor()
                + "',bookTypeId=" + book.getBookTypeId() + " where id="
                + book.getId();  // ctrl+a 全选  ctrl+shift+F 格式化代码
        Statement stmt = con.createStatement(); // 创建Statement
        int result = stmt.executeUpdate(sql);
        dbUtil.close(stmt, con); // 关闭Statement和连接
        return result;
    }

    public static void main(String[] args) throws Exception{
        Book book=new Book(3,"Java牛牛2222", 121, "牛哥222", 1);
        int result=updateBook(book);
        if(result==1){
            System.out.println("更新成功!");
        }else{
            System.out.println("更新败!");
        }
    }
}
使用statment 接口实现删除数据操作
public class Demo1 {

    private static DbUtil dbUtil=new DbUtil();
    private static int deleteBook(int id)throws Exception{
        Connection con = dbUtil.getCon(); // 获取连接
        String sql ="delete from t_book where id="+id;
        Statement stmt = con.createStatement(); // 创建Statement
        int result = stmt.executeUpdate(sql);
        dbUtil.close(stmt, con); // 关闭Statement和连接
        return result;
    }
    
    public static void main(String[] args) throws Exception{
        int result=deleteBook(3);
        if(result==1){
            System.out.println("删除成功!");
        }else{
            System.out.println("删除失败!");
        }
    }
}

 

ResultSet:
调用Statement对象的executeQuery()方法创建一个ResultSet对象。封装了执行数据库操作的结果集。ResultSet对象维护了一个指向当前数据行的游标,初始化时,游标在第一行之前,通过ResultSet对象的next()方法移动游标到下一行。

ResultSet 结果集的引入--查询数据库时,返回的是一个二维的结果集,我们这时候需要使用来遍历ResultSet结果集,获取每一行的数据。

String getString(int columnIndex) 以Java 编程语言中String 的形式获取此ResultSet 对象的当前行中指定列的值。

String getString(String columnLabel) 以Java 编程语言中String 的形式获取此ResultSet 对象的当前行中指定列的值。

public class Demo1 {

    private static DbUtil dbUtil = new DbUtil();
    /**
     * 1.遍历查询结果
     * @throws Exception
     */
    private static void listBook() throws Exception {
        Connection con = dbUtil.getCon(); // 获取连接
        String sql = "select * from t_book";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery(); // 返回结果集ResultSet
        while (rs.next()) {
            int id = rs.getInt(1); // 获取第一个列的值 编号id
            String bookName = rs.getString(2); // 获取第二个列的值 图书名称 bookName
            float price = rs.getFloat(3); // 获取第三列的值 图书价格 price
            String author = rs.getString(4); // 获取第四列的值 图书作者 author
            int bookTypeId = rs.getInt(5); // 获取第五列的值 图书类别id
            System.out.println("图书编号:" + id + " 图书名称:" + bookName + " 图书价格:"
                    + price + " 图书作者:" + author + " 图书类别id:" + bookTypeId);
            System.out
                    .println("=======================================================================");

        }
    }
    
    /**
     *2.遍历查询结果
     * @throws Exception
     */
    private static void listBook2() throws Exception {
        Connection con = dbUtil.getCon(); // 获取连接
        String sql = "select * from t_book";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery(); // 返回结果集ResultSet
        while (rs.next()) {
            int id = rs.getInt("id"); // 获取第一个列的值 编号id
            String bookName = rs.getString("bookName"); // 获取第二个列的值 图书名称 bookName
            float price = rs.getFloat("price"); // 获取第三列的值 图书价格 price
            String author = rs.getString("author"); // 获取第四列的值 图书作者 author
            int bookTypeId = rs.getInt("bookTypeId"); // 获取第五列的值 图书类别id
            System.out.println("图书编号:" + id + " 图书名称:" + bookName + " 图书价格:"
                    + price + " 图书作者:" + author + " 图书类别id:" + bookTypeId);
            System.out.println("=========================================================");

        }
    }
    /*
     *3.遍历查询结果
     */
    private static List<Book> listBook3()throws Exception{
        List<Book> bookList=new ArrayList<Book>(); 
        Connection con = dbUtil.getCon(); // 获取连接
        String sql = "select * from t_book";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery(); // 返回结果集ResultSet
        while (rs.next()) {
            int id = rs.getInt("id"); // 获取第一个列的值 编号id
            String bookName = rs.getString("bookName"); // 获取第二个列的值 图书名称 bookName
            float price = rs.getFloat("price"); // 获取第三列的值 图书价格 price
            String author = rs.getString("author"); // 获取第四列的值 图书作者 author
            int bookTypeId = rs.getInt("bookTypeId"); // 获取第五列的值 图书类别id
            Book book=new Book(id, bookName, price, author, bookTypeId);
            bookList.add(book);
        }
        return bookList;
    }

    public static void main(String[] args) throws Exception {
        // listBook();
        // listBook2();
        List<Book> bookList=listBook3();
        for (Book book : bookList) {
            System.out.println(book);
        }
    }
}

例子:

//数据库连接
public class DbUtil {
    // 数据库地址
    private static String dbUrl="jdbc:mysql://localhost:3306/db_book";
    // 用户名
    private static String dbUserName="root";
    // 密码
    private static String dbPassword="123456";
    // 驱动名称
    private static String jdbcName="com.mysql.jdbc.Driver";
    
    /**
     * 获取数据库连接
     * @return
     * @throws Exception
     */
    public Connection getCon()throws Exception{
        Class.forName(jdbcName);
        Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        return con;
    }
    
    /**
     * 关闭连接
     * @param con
     * @throws Exception
     */
    public void close(Statement stmt,Connection con)throws Exception{
        if(stmt!=null){
            stmt.close();
            if(con!=null){
                con.close();
            }
        }
    }
    
    /**
     * 关闭连接
     * @param con
     * @throws Exception
     */
    public void close(PreparedStatement pstmt,Connection con)throws Exception{
        if(pstmt!=null){
            pstmt.close();
            if(con!=null){
                con.close();
            }
        }
    }
}
图书模型:
public class Book {

    private int id;
    private String bookName;
    private float price;
    private String author;
    private int bookTypeId;
    private File context;
    private File pic;
    
    public Book(int id, String bookName, float price, String author,int bookTypeId) {
        super();
        this.id = id;
        this.bookName = bookName;
        this.price = price;
        this.author = author;
        this.bookTypeId = bookTypeId;
    }
    public Book(String bookName, float price, String author, int bookTypeId) {
        super();
        this.bookName = bookName;
        this.price = price;
        this.author = author;
        this.bookTypeId = bookTypeId;
    }
    
    
    public Book(String bookName, float price, String author, int bookTypeId,
            File context) {
        super();
        this.bookName = bookName;
        this.price = price;
        this.author = author;
        this.bookTypeId = bookTypeId;
        this.context = context;
    }
    
    
    public Book(String bookName, float price, String author, int bookTypeId,File context, File pic) {
        super();
        this.bookName = bookName;
        this.price = price;
        this.author = author;
        this.bookTypeId = bookTypeId;
        this.context = context;
        this.pic = pic;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getBookTypeId() {
        return bookTypeId;
    }
    public void setBookTypeId(int bookTypeId) {
        this.bookTypeId = bookTypeId;
    }
    
    
    public File getContext() {
        return context;
    }
    public void setContext(File context) {
        this.context = context;
    }
    public File getPic() {
        return pic;
    }
    public void setPic(File pic) {
        this.pic = pic;
    }
    @Override
    public String toString() {
        return "["+this.id+","+this.bookName+","+this.price+","+this.author+","+this.bookTypeId+"]";
    }
}
在CLOB中---可以存储大字符数据对象,小说;
public class Demo1 {

private static DbUtil dbUtil=new DbUtil();
    
    /**
     * 添加图书
     * @param book
     * @return
     * @throws Exception
     */
    private static int addBook(Book book)throws Exception{
        Connection con=dbUtil.getCon(); // 获取连接
        String sql="insert into t_book values(null,?,?,?,?,?)";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, book.getBookName());  // 给第一个坑设置值
        pstmt.setFloat(2, book.getPrice());  // 给第二个坑设置值
        pstmt.setString(3, book.getAuthor()); // 给第三个坑设置值
        pstmt.setInt(4, book.getBookTypeId());  // 给第四个坑设置值
        File context=book.getContext(); // 获取文件
        InputStream inputStream=new FileInputStream(context);
        pstmt.setAsciiStream(5, inputStream,context.length());  // 给第五个坑设置值
        int result=pstmt.executeUpdate();
        dbUtil.close(pstmt, con);
        return result;
    }
    
    public static void getBook(int id)throws Exception{
        Connection con=dbUtil.getCon();
        String sql="select * from t_book where id=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setInt(1, id);
        ResultSet rs=pstmt.executeQuery();
        if(rs.next()){
            String bookName=rs.getString("bookName");
            float price=rs.getFloat("price");
            String author=rs.getString("author");
            int bookTypeId=rs.getInt("bookTypeId");
            Clob c=rs.getClob("context");
            String context=c.getSubString(1, (int)c.length());
            System.out.println("图书名称:"+bookName);
            System.out.println("图书价格:"+price);
            System.out.println("图书作者:"+author);
            System.out.println("图书类型ID:"+bookTypeId);
            System.out.println("图书内容:"+context);
        }
        dbUtil.close(pstmt, con);
    }
    
public static void main(String[] args)throws Exception {
        File context=new File("c:/helloWorld.txt");
        Book book=new Book("helloWorld", 100, "小锋", 1,context);
        int result=addBook(book);
        if(result==1){
            System.out.println("添加成功!");
        }else{
            System.out.println("添加失败!");
        }
        getBook(16); }
在BLOB 中可以存放二进制大数据对象,比如图片,电影,音乐;
public class Demo1 {

private static DbUtil dbUtil=new DbUtil();
    /**
     * 添加图书
     * @param book
     * @return
     * @throws Exception
     */
    private static int addBook(Book book)throws Exception{
        Connection con=dbUtil.getCon(); // 获取连接
        String sql="insert into t_book values(null,?,?,?,?,?,?)";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, book.getBookName());  // 给第一个坑设置值
        pstmt.setFloat(2, book.getPrice());  // 给第二个坑设置值
        pstmt.setString(3, book.getAuthor()); // 给第三个坑设置值
        pstmt.setInt(4, book.getBookTypeId());  // 给第四个坑设置值
        File context=book.getContext(); // 获取文件
        InputStream inputStream=new FileInputStream(context);
        pstmt.setAsciiStream(5, inputStream,context.length());  // 给第五个坑设置值
        
        File pic=book.getPic(); // 获取图片文件
        InputStream inputStream2=new FileInputStream(pic);
        pstmt.setBinaryStream(6, inputStream2, pic.length()); // 给第六个坑设置值
        int result=pstmt.executeUpdate();
        dbUtil.close(pstmt, con);
        return result;
    }
    
    public static void getBook(int id)throws Exception{
        Connection con=dbUtil.getCon();
        String sql="select * from t_book where id=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setInt(1, id);
        ResultSet rs=pstmt.executeQuery();
        if(rs.next()){
            String bookName=rs.getString("bookName");
            float price=rs.getFloat("price");
            String author=rs.getString("author");
            int bookTypeId=rs.getInt("bookTypeId");
            Clob c=rs.getClob("context");
            String context=c.getSubString(1, (int)c.length());
            Blob b=rs.getBlob("pic");
            FileOutputStream out=new FileOutputStream(new File("d:/pic2.jpg"));
            out.write(b.getBytes(1, (int)b.length()));
            out.close();
            System.out.println("图书名称:"+bookName);
            System.out.println("图书价格:"+price);
            System.out.println("图书作者:"+author);
            System.out.println("图书类型ID:"+bookTypeId);
            System.out.println("图书内容:"+context);
        }
        dbUtil.close(pstmt, con);
    }
    
    public static void main(String[] args)throws Exception {
        File context=new File("c:/helloWorld.txt");
        File pic=new File("c:/pic1.jpg");
        Book book=new Book("helloWorld", 100, "小锋", 1,context,pic);
        int result=addBook(book);
        if(result==1){
            System.out.println("添加成功!");
        }else{
            System.out.println("添加失败!");
        }
        getBook(18);
    }
}

 

 

PreparedStatement
PreparedStatement从Statement接口继承来,调用Connection对象的prepareStatement方法来得到PreparedStatement对象,PreparedStatement对象所代表的SQL语句中的参数用?来表示。调用PreparedStatement对象的setXXX方法来设置参数。setXXX第一个参数是参数的索引(从1开始),第二个参数要设置的是参数的值。

数据库的连接:
public class DbUtil {
    // 数据库地址
    private static String dbUrl="jdbc:mysql://localhost:3306/db_book";
    // 用户名
    private static String dbUserName="root";
    // 密码
    private static String dbPassword="123456";
    // 驱动名称
    private static String jdbcName="com.mysql.jdbc.Driver";
    
    /**
     * 获取数据库连接*/
    public Connection getCon()throws Exception{
        Class.forName(jdbcName);
        Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        return con;
    }
    
    /**
     * 关闭连接
     */
    public void close(PreparedStatement pstmt,Connection con)throws Exception{
        if(pstmt!=null){
            pstmt.close();
            if(con!=null){
                con.close();
            }
        }
    }
}
图书模型:
public class Book {

    private int id;
    private String bookName;
    private float price;
    private String author;
    private int bookTypeId;
    
    public Book(int id, String bookName, float price, String author,int bookTypeId) {
        super();
        this.id = id;
        this.bookName = bookName;
        this.price = price;
        this.author = author;
        this.bookTypeId = bookTypeId;
    }
    public Book(String bookName, float price, String author, int bookTypeId) {
        super();
        this.bookName = bookName;
        this.price = price;
        this.author = author;
        this.bookTypeId = bookTypeId;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getBookTypeId() {
        return bookTypeId;
    }
    public void setBookTypeId(int bookTypeId) {
        this.bookTypeId = bookTypeId;
    }
}
使用PreparedStatement 接口实现添加数据操作
public class Demo1 {
    private static DbUtil dbUtil=new DbUtil();
    private static int addBook(Book book)throws Exception{
        Connection con=dbUtil.getCon(); // 获取连接
        String sql="insert into t_book values(null,?,?,?,?)";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, book.getBookName());  // 给第一个坑设置值
        pstmt.setFloat(2, book.getPrice());  // 给第二个坑设置值
        pstmt.setString(3, book.getAuthor()); // 给第三个坑设置值
        pstmt.setInt(4, book.getBookTypeId());  // 给第四个坑设置值
        int result=pstmt.executeUpdate();
        dbUtil.close(pstmt, con);
        return result;
    }
    
    public static void main(String[] args) throws Exception{
        Book book=new Book("Java叉叉2", 1, "叉叉", 1);
        int result=addBook(book);
        if(result==1){
            System.out.println("添加成功!");
        }else{
            System.out.println("添加失败!");
        }
    }
}
使用PreparedStatement 接口实现更新数据操作
public class Demo1 {
    private static DbUtil dbUtil=new DbUtil();
    private static int updateBook(Book book)throws Exception{
        Connection con=dbUtil.getCon();
        String sql="update t_book set bookName=?,price=?,author=?,bookTypeId=? where id=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, book.getBookName());
        pstmt.setFloat(2, book.getPrice());
        pstmt.setString(3, book.getAuthor());
        pstmt.setInt(4, book.getBookTypeId());
        pstmt.setInt(5, book.getId());
        int result=pstmt.executeUpdate();
        dbUtil.close(pstmt, con);
        return result;
    }
    
    public static void main(String[] args) throws Exception{
        Book book=new Book(12,"K2", 2, "K", 2);
        int result=updateBook(book);
        if(result==1){
            System.out.println("更新成功!");
        }else{
            System.out.println("更新失败!");
        }
    }
}
使用PreparedStatement 接口实现删除数据操作
public class Demo1 {
    private static DbUtil dbUtil=new DbUtil();
    private static int deleteBook(int id)throws Exception{
        Connection con=dbUtil.getCon();
        String sql="delete from t_book where id=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setInt(1, id);
        int result=pstmt.executeUpdate();
        dbUtil.close(pstmt, con);
        return result;
    }
    
    public static void main(String[] args)throws Exception {
        int result=deleteBook(12);
        if(result==1){
            System.out.println("删除成功!");
        }else{
            System.out.println("删除失败!");
        }
    }
}

 

 

CallableStatement:
CallableStatement对象从PreparedStatement接口继承。调用Connection对象的preparecall方法得到CallableStatement对象。

public class Demo1 {
    private static DbUtil dbUtil=new DbUtil();
    /**
     * 调用存储过程,通过id查询bookName
     * @param id
     * @return
     * @throws Exception
     */
    private static String getBookNameById(int id)throws Exception{
        Connection con=dbUtil.getCon();  // 获取数据库连接
        String sql="{CALL pro_getBookNameById(?,?)}";
        CallableStatement cstmt=con.prepareCall(sql);
        cstmt.setInt(1, id); // 设置第一个参数
        cstmt.registerOutParameter(2, Types.VARCHAR);  // 设置返回类型
        cstmt.execute();
        String bookName=cstmt.getString("bN");  // 获取返回值
        dbUtil.close(cstmt, con);
        return bookName;
    }
    
    public static void main(String[] args) throws Exception{
        System.out.println("图书名称是:"+getBookNameById(11));
    }
}

 


元数据:ResultSetMetaData,用于获取描述数据库结构的元素据。在SQL中,用于描述数据库,或者它的各个组成部分之一的数据称为元数据。


ResultSet对象的getMetaData方法得到ResultSetMetaData对象。ResultSetMetaData接口的方法:
getColumnName---返回列的名称。
getColumnCount---返回结果集中的列数。
getColumnDisplaySize---返回列的最大字符宽度
getColumnType---返回列的sql类型。。。。。。。。

public class Demo2 {
    public static void main(String[] args) throws Exception{
        DbUtil dbUtil=new DbUtil();
        Connection con=dbUtil.getCon();
        String sql="select * from t_book";
        PreparedStatement pstmt=con.prepareStatement(sql);
        ResultSetMetaData rsmd=pstmt.getMetaData();
        int num=rsmd.getColumnCount(); // 获取元数据列的总数
        System.out.println("共有"+num+"列");
        for(int i=1;i<=num;i++){
            System.out.println(rsmd.getColumnName(i)+","+rsmd.getColumnTypeName(i));
        }
    }
}

 


事务处理:
保证所有的事务都作为一个工作单元来执行。
调用Connection对象的setAutoCommit方法,传入false来取消自动提交的事务。在所有的sql语句成功执行后,调用Connection对象的commit方法提交事务,或者在执行出错时,调用Connection对象的rollback方法回滚事务。

事务:事务本身具有原子性(Atomicity)、一致性(Consistency)、隔离性或独立性(Isolation)、持久性(Durability)4 个特性,这4 个特性也被称为ACID 特征。

原子性:原子性是事务最小的单元,是不可再分隔的单元,相当于一个个小的数据库操作,这些操作必须同时

成功,如果一个失败了,则一切的操作将全部失败。

一致性:指的是在数据库操作的前后是完全一致的,保证数据的有效性,如果事务正常操作则系统会维持有效

性,如果事务出现了错误,则回到最原始状态,也要维持其有效性,这样保证事务开始时和结束时系统处于一

致状态。

隔离性:多个事务可以同时进行且彼此之间无法访问,只有当事务完成最终操作时,才可以看到结果;

持久性:事务完成之后,它对于系统的影响是永久性的。该修改即使出现致命的系统故障也将一直保持。

public class Demo1 {
    
    private static DbUtil dbUtil=new DbUtil();
    /**
     * 转出
     * @param con
     * @param accountName
     * @param account
     * @throws Exception
     */
    private static void outCount(Connection con,String accountName,int account)throws Exception{
        String sql="update t_account set accountBalance=accountBalance-? where accountName=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setInt(1, account);
        pstmt.setString(2, accountName);
        pstmt.executeUpdate();
    }
    /**
     * 转入
 * @param con
     * @param accountName
     * @param account
     * @throws Exception
     */
    private static void inCount(Connection con,String accountName,int account)throws Exception{
        String sql="update t_account set account=accountBalance+? where accountName=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setInt(1, account);
        pstmt.setString(2, accountName);
        pstmt.executeUpdate();
    }
    
    public static void main(String[] args) {
        Connection con=null;
        try {
            con=dbUtil.getCon(); 
            con.setAutoCommit(false); // 取消自动提交
            System.out.println("张三开始向李四转账!");
            int account=500;
            outCount(con, "张三", account);
            inCount(con, "李四", account);
            System.out.println("转账成功!");
        } catch (Exception e) {
            try {
                con.rollback(); // 回滚
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                con.commit();  // 提交事务
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

事务保存点
public class Demo1 {
    private static DbUtil dbUtil=new DbUtil();
    /**
     * 转出
     * @param con
     * @param accountName
     * @param account
     * @throws Exception
     */
    private static void outCount(Connection con,String accountName,int account)throws Exception{
        String sql="update t_account set accountBalance=accountBalance-? where accountName=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setInt(1, account);
        pstmt.setString(2, accountName);
        pstmt.executeUpdate();
    }
    /**
     * 转入
     * @param con
     * @param accountName
     * @param account
     * @throws Exception
     */
    private static void inCount(Connection con,String accountName,int account)throws Exception{
        String sql="update t_account set account=accountBalance+? where accountName=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setInt(1, account);
        pstmt.setString(2, accountName);
        pstmt.executeUpdate();
    }
    
    
    public static void main(String[] args) {
        Connection con=null;
        Savepoint sp=null;
        try {
            con=dbUtil.getCon(); 
            con.setAutoCommit(false); // 取消自动提交
            System.out.println("张三开始向李四转账!");
            int account=500;
            outCount(con, "张三", account);
            sp=con.setSavepoint(); // 设置一个保存点
            inCount(con, "李四", account);
            System.out.println("转账成功!");
        } catch (Exception e) {
            try {
                con.rollback(sp); // 回滚到sp保存点
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            try {
                con.commit();  // 提交事务
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

 


修改表的存储引擎:alter table 表明 engine=innodb

 

 

mysql对中文的处理:mysqld --character_set_server=gbk

 

 

 

 

 

DatabaseMetaData 可以得到数据库的一些基本信息,包括数据库的名称、版本,以及得到表的信息。

String getDatabaseProductName() 获取此数据库产品的名称。

int getDriverMajorVersion() 获取此JDBC 驱动程序的主版本号。

int getDriverMinorVersion() 获取此JDBC 驱动程序的次版本号。

public class Demo1 {
    public static void main(String[] args)throws Exception {
        DbUtil dbUtil=new DbUtil();
        Connection con=dbUtil.getCon();
        DatabaseMetaData dmd=con.getMetaData(); // 获取元数据
        System.out.println("数据库名称:"+dmd.getDatabaseProductName());
        System.out.println("数据库版本:"+dmd.getDriverMajorVersion()+"."+dmd.getDriverMinorVersion());
        
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2015-03-16 22:08  肉球  阅读(198)  评论(0编辑  收藏  举报