使用PreparedStatement访问MySQL数据库

使用PreparedStatement访问MySQL数据库

进行增删改查操作



package study;

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

public class JDBCdemo {
	private final String USERNAME = "root";
	private final String PASSWORD = "123456";
	private final String URL = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
	Connection connection = null;
	PreparedStatement pStatement = null;
	ResultSet rs = null;

	public void query() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
			String sql = "select * from user where uname like ?";// 查询
			String sql2 = "delete from user where uid=?";// 删除
			String sql3 = "update user set uname= ? where uid=?";// 修改
			String sql4 = "insert into user values(?,?,?)";// 插入

			pStatement = connection.prepareStatement(sql);
			// 插入用的数据
//				pStatement.setInt(1, 2);
//				pStatement.setString(2, "张峰");
//				pStatement.setString(3, "女");
			// 查询用的数据
			pStatement.setString(1, "%峰%");// 模糊查询
			rs = pStatement.executeQuery();// 查询
			// int executeUpdate= pStatement.executeUpdate();//增删改用的
			while (rs.next()) { // 查询用的
				System.out.print(rs.getInt("uid") + "\t");
				System.out.print(rs.getString("uname") + "\t");
				System.out.print(rs.getString("usex") + "\t");
				System.out.println("操作成功");
			}
			// 增删改用的
//			if(executeUpdate!=0) {
//				System.out.println("操作成功");
//			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {// 后打开的先关闭
			try {
				if (rs != null)
					rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if (pStatement != null)
					pStatement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}


执行结果如下:
执行结果

发布了32 篇原创文章 · 获赞 1 · 访问量 2820

猜你喜欢

转载自blog.csdn.net/YOUAREHANDSOME/article/details/104822086