java preparestatment 可以重复使用

来源:互联网 发布:广联达软件有哪些 编辑:程序博客网 时间:2024/04/29 22:18
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement;public class MysqlTest {public static void main(String[] args) throws Exception {testPrepareStatement();}public static void testPrepareStatement() {Connection conn = getConnection();PreparedStatement ps = null;try {String sql = "delete from test";ps = conn.prepareStatement(sql);ps.executeUpdate();close(ps);String insertStr = "insert into test(id,name) values(?,?)";ps = conn.prepareStatement(insertStr);ps.setInt(1, 1);ps.setString(2, "dandan");ps.execute();close(ps);} catch (Exception e) {e.printStackTrace();} finally {close(conn);}}public static Connection getConnection() {Connection conn = null;try {Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";conn = DriverManager.getConnection(url, "root", "test");} catch (Exception e) {e.printStackTrace();}return conn;}// 关闭 Connection 和 Statement public static void close(Connection conn,Statement st) {if(conn!=null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}if(st!=null) {try {st.close();} catch (SQLException e) {e.printStackTrace();}}}
        // 关闭 Connection public static void close(Connection conn) {if(conn!=null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}
        // 关闭 Statement public static void close(Statement st) {if(st!=null) {try {st.close();} catch (SQLException e) {e.printStackTrace();}}}}

0 0
原创粉丝点击