JDBC的入门

来源:互联网 发布:office2007卸载软件 编辑:程序博客网 时间:2024/06/06 17:37

JDBC 即Java Data Base Connectivity,java数据库连接;


步骤一:建立JavaBean

public static Connection getCon(){        String driver = "com.mysql.jdbc.Driver";        String url = "jdbc:mysql://localhost:3306/chatrecord";        String username = "root";        String password = "";        Connection conn = null;        try {            Class.forName(driver);            conn = (Connection) DriverManager.getConnection(url, username, password);        }        catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return conn;    }


步骤二:建立与数据库的连接

public static Connection getCon(){        String driver = "com.mysql.jdbc.Driver";        String url = "jdbc:mysql://localhost:3306/chatrecord";        String username = "root";        String password = "";        Connection conn = null;        try {            Class.forName(driver);            conn = (Connection) DriverManager.getConnection(url, username, password);        }        catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return conn;    }

步骤三:对数据进行增删改查(以增为例)

 public static int insert(MessageBean message){                Connection con = getCon();        String sql = "insert into chatrecord(id,message) values (?,?,?);";        PreparedStatement ps = null;        int i = 0;        try{            ps = (PreparedStatement)con.prepareStatement(sql);            ps.setString(1, message.getId());            ps.setString(2, message.getContent());            i = ps.executeUpdate();            ps.close();            con.close();        }catch(SQLException e){            e.printStackTrace();        }}



0 0
原创粉丝点击