Java连接MySql数据库

所需jar包:

mysql-connector-java-5.1.27.jar

代码:

String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
String sql1 = "INSERT...";
String sql2 = "SELECT...";

Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);

//以下两种方式均可
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql1);

PreparedStatement pstmt = conn.prepareStatement(sql2);
ResultSet rs = pstmt.executeQuery();

//最后注意关闭
rs.close();
pstmt.close();
stmt.close();
conn.close();
posted @ 2014-07-21 15:38  小样儿1020  阅读(224)  评论(0编辑  收藏  举报