JDBC--Statement(添加)(二)

2014-11-24 11:35:13 · 作者: · 浏览: 2
} } public static void main(String[] args) throws Exception { User user=new User(5, "java6", "123456"); add(user); } }
运行结果

\

第四种方法(是不是有的代码写重复了)

DbUtil

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

public class DbUtil {
	public static Connection getConnection() throws Exception {
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/db_book";
			con = DriverManager.getConnection(url, "root", "123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}
	public static void close(Connection con,Statement stat){
		try {
			stat.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
import java.sql.Connection;
import java.sql.Statement;

public class DataInsert4 {
	private static void add(User user) throws Exception {
		Connection con = null;
		Statement stat = null;
		try {
			con=DbUtil.getConnection();
			stat = con.createStatement();
			String sql = "insert into t_user values(" + user.getId() + ",'"
					+ user.getUserName() + "','" + user.getPassword() + "')";
			stat.executeUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtil.close(con, stat);
		}
	}

	public static void main(String[] args) throws Exception {
		User user=new User(6, "java7", "123456");
		add(user);
	}
}

运行结果:

\