使用PreparedStatement操作数据库

package com.jdbc;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
/**
 * why?
 * 因为使用Statement拼写很费事,且容易出错
 * 有效防止注入
 * @author 超超啊
 *使用PreparedStatement
 *1,创建PreoaredStatement
 *String sql="insert into t_user values (?,?,?,?)";
 *PreparedStatement ps=conn.PreparedStatement(sql);
 *2,调用PreparedStatement的setxxx(int index,Object val);设置占位符的值,索引值从1开始.
 *3,执行SQL语句:executeQuery()或executeUpdate().注意:执行时不需要在传入SQL语句
 */
public class JDBCtest03_PreparedStatement {
	public static void main(String[] args) {
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn=(Connection) DriverManager.getConnection("jdbc:mysql:///testjdbc","root","cchaos");
			String sql="insert into t_user (id,username,pwd,rgtime) values (?,?,?,?)";
			ps=(PreparedStatement) conn.prepareStatement(sql);
			ps.setInt(1, 10);
			ps.setString(2, "li");
			ps.setString(3, "chaos");
			ps.setString(4, now());
			ps.executeUpdate();
			System.out.println("操作完成!"); 
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static String now() {
		// TODO Auto-generated method stub
		return null;
	}

}

你可能感兴趣的:(JAVA,MySQL,JDBC)