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

JDBC连接mysql

个人开发时主要还是使用mysql,所以就顺便把连接mysql的操作,记录下来,算备忘吧

其实主要有的操作包括

1、配置好环境,主要是安装mysql和下载连接需要的包(我用的是mysql-connector-java-5.1.3-rc-bin.jar)

2、注册驱动? Class.forName("com.jdbc.mysql.Driver");

3、创建连接? Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test",user,password);

4、创建表达式 Statement stmt = con.createStatement();

5、执行sql语句并获得相应的结果集 ResultSet rs = stmt.executeQuery("select * from tables");

6、获取结果while(rs.next()){System.out.println(rs.getString(1));}

7、关闭连接rs.close();stmt.close();con.close();

代码如下:

package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJDBC {
	public static void main(String[] args) {
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/train",
					"xxx", "yyyy");
			stmt = con.createStatement();
			rs = stmt.executeQuery("select * from tbl_user");
			while (rs.next()) {
				String str = rs.getString(2);
				System.out.println(str);
				String uname = rs.getString("uname");
				System.out.println(uname);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null){
					rs.close();
					rs = null;
				}
				if (stmt != null){
					stmt.close();
					stmt = null;
				}
				if (con != null){
					con.close();
					stmt = null;
				}
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
		}
	}
}

在jdbc中能够对事务进行处理:
con.setAutoCommit(false);
......
con.commit();
con.setAutoCommit(true);
这样就实现了,对事务的操作。

还有jdbc中批处理操作
Statement stmt = con.createStatement();
stmt.addBatch(sql语句);
stmt.executeBatch();

或者是
PreparedStatement pstmt = con.preparedStatement("insert into table_a values(?,?)");
pstmt.setInt(1,xxx);
pstmt.setString(2,yyy);
pstmt.addBatch();
pstmt.excuteBatch();