日期:2014-05-16  浏览次数:20434 次

java, jdbc方式连接mysql
用于测试的代码,成功运行,之后做的工作是进行封装,使其更容易用

maven:
这里有一个诡异的问题:5.1.25;5.1.24死活都下载有问题

<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.23</version>
    </dependency>



java:
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; 
	    }
	}