日期:2014-05-16 浏览次数:20438 次
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.23</version> </dependency>
try { Class.forName("com.mysql.jdbc.Driver").newInstance(); //Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/pandora?user=root&password=hustacm!@#$%"); String url = "jdbc:mysql://localhost/pandora"; String user = "root"; String password = "hustacm!@#$%"; Connection conn = DriverManager.getConnection(url, user, password); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * from account"); System.out.println("in account "); while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)); } //good way 1 stmt.execute("INSERT INTO account (username, password) VALUES('tigerhy2', 'tigerhyx')"); //good way 2 stmt.execute("INSERT INTO account VALUES(19, 'tigerhy3', 'tigerhyx')"); //good way 3 String sql = "INSERT INTO account (username, password) VALUES (?,?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, "tigerhy4"); pstmt.setString(2, "tigerhy4"); int x = pstmt.executeUpdate(); //stmt.execute(arg0, arg1); } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } finally { if (rs != null) { try{ rs.close(); } catch (SQLException sqlEx) { } rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { } stmt = null; } }