`
illidantorch
  • 浏览: 12890 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

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



这哥们写的教程都还不错:
http://tutorials.jenkov.com/jdbc/index.html

最大的收获是:PreparedStatement,对数据库操作的时候,多用这个。


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics