首页 > 代码库 > Java连接MySql数据库

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(sql1);ResultSet rs = pstmt.executeQuery();//最后注意关闭rs.close();pstmt.close();stmt.close();conn.close();