Java 笔记----数据库操作(一)

来源:互联网 发布:淘宝店家信誉等级 编辑:程序博客网 时间:2024/06/15 04:01

一、基本概念

1、JDBC 的全称 是Java Database Connectivity ,即Java数据库连接,它是一种可以执行SQL语句的java API。 程序可通过JDBC API连接到关系数据库,并使用结构化查询语言(SQL,数据库标准的查询语言)来完成对数据库的查询、更新。

2、JDBC 三个基本工作:

1)建立与数据库连接;
2)执行SQL语句;
3)获得SQL语句的执行结果。

二、连接数据库步骤:

添加MySQL JDBC
以MySQL数据库为例:

import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Date;import com.mysql.jdbc.Connection;public class JDBCTest {    //数据库连接    private Connection con = null;    //声明    private PreparedStatement sql;    //执行结果    private ResultSet res;    public JDBCTest() {        con = getConnection();// 连接数据库        /**         * 执行语句         */        closeData();// 关闭连接,避免数据库一直连接    }    /**     * 127.0.0.1是本地IP地址,选择localhost 不经过网卡 连接数据库     *      *      * @return com.mysql.jdbc.Connection     */    public Connection getConnection() {        Connection conn = null;        try {            // 加载驱动            Class.forName("com.mysql.jdbc.Driver");            java.lang.String dbname = "数据库名";            String url = "jdbc:mysql://127.0.0.1:3306/" + dbname + "?useUnicode=true&characterEncoding=UTF-8";            // &autoReconnect=true            conn = (Connection) DriverManager.getConnection(url, "root", "bstek");            // 开启事务            conn.setAutoCommit(false);        } catch (Exception e) {            System.err.println("连接数据库有误!!");        }        return conn;    }    /**     * 获取错误的account 例如:sql_str="select * from table name where status =0"     *      * @return collection<Account> account     * @throws SQLException     */    public void query(String sql_str) throws SQLException {        sql = con.prepareStatement(sql_str);        res = sql.executeQuery();        con.commit();        while (res.next()) {            res.getString(1);// columnIndex执行效率比下面高            res.getString("columnLabel");        }    }    /**     * 先查询,后更新     *      * @param date     * @param name     * @param id     */    public void update1(Date date, String name, int id) {        try {            sql = con.prepareStatement("select * from tablename where id =  " + id, ResultSet.TYPE_SCROLL_INSENSITIVE,                    ResultSet.CONCUR_UPDATABLE);            res = sql.executeQuery();            con.commit();            if (res.next()) {                res.updateString(2, name);                res.updateDate(3, date);                res.updateRow();            }        } catch (SQLException e) {            try {                con.rollback();            } catch (SQLException e1) {                e1.printStackTrace();            }            e.printStackTrace();        }    }    /**     * 直接使用sql语句set更新 tablename 使用的时候 要换成具体的表名     *      * @param name     * @param Id     */    public void update2(String name, int Id) {        try {            String sql_Str = "update tablename set name='" + name + "' where id ='" + Id + "'";            sql = con.prepareStatement(sql_Str);            sql.executeUpdate();            con.commit();        } catch (SQLException e) {            try {                con.rollback();            } catch (SQLException e1) {                e1.printStackTrace();            }            e.printStackTrace();        }    }    /**     *      * @param number     * @param Name     * @param id     */    public void insert(String number, String Name, int id) {        try {            sql = con.prepareStatement(                    // 问号的数量 等于 数据表的数量                    "insert into tablename value(?,?,?)");            sql.setInt(1, id);            sql.setString(2, Name);            sql.setString(3, number);            sql.executeUpdate();            con.commit();        } catch (SQLException e) {            try {                // 数据库回滚                con.rollback();            } catch (SQLException e1) {                // TODO Auto-generated catch block                e1.printStackTrace();            }            e.printStackTrace();        }    }    /**     * 删除数据库     *      * @param name     */    public void delete(String name) {        try {            sql = con.prepareStatement("delete from 表名 where name= " + name);            sql.executeUpdate();            con.commit();        } catch (SQLException e) {            try {                con.rollback();            } catch (SQLException e1) {                e1.printStackTrace();            }            System.err.println("报错");        }    }    /**     * 关闭数据库 连接     */    public void closeData() {        // 关闭记录集        if (res != null) {            try {                res.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        // 关闭声明        if (sql != null) {            try {                sql.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        // 关闭链接对象        if (con != null) {            try {                con.close();            } catch (SQLException e) {                e.printStackTrace();            }        }    }}