MyEclipse通过JDBC连接Mysql

1、导入驱动JAR包

mysql-connector-java-5.1.10-bin.jar

2、新建一个DB辅助类:DbHelper.java


publicstatic Connection getConnection() {
    Connection conn = null;
    try {       
        //第一步:加载MySQL的JDBC的驱动
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test";        
        String username = "root";
        String password = "root";
        //第二步:创建与MySQL数据库的连接类的实例
        conn = DriverManager.getConnection(url, username, password);        
    } catch (Exception e) {
        // TODO: handle exception
    }
        return conn;
}
注意:如果保存到数据库的数据出现乱码:需要在数据库后面加上 ?useUnicode=true&characterEncoding=UTF-8

3、操作 — 增删改查


// 增:
PreparedStatement ps=null;        
conn = SqlUtil.getConnection();
String sql = "insert into table values(?,?);";
ps = conn.prepareStatement(sql);
ps.setString(1, value);
ps.setLong(2, value);
int num = ps.executeUpdate(); //返回受影响的行数

// 删:
PreparedStatement ps=null;
conn = SqlUtil.getConnection();
String sql="delete from Article where id=?";
ps=conn.prepareStatement(sql);
ps.setInt(1, id);
int i=ps.executeUpdate();//返回受影响的行数

// 改:
PreparedStatement ps=null;
String sql="update table set title=?  where id=?";
conn = SqlUtil.getConnection();
ps=conn.prepareStatement(sql);
ps.setString(1, article.getTitle());
ps.setInt(3, article.getId());
int i=ps.executeUpdate();//返回受影响的行数

// 查:
Connection con = SqlUtil.getConnection();            
Statement sql_statement = con.createStatement();
String query = "select * from student";            
ResultSetresult = sql_statement.executeQuery(query);
while (result.next()) {
    String name  = result.getString("name");
}

发表评论

Blue Captcha Image
Refresh

*