JDBC实现按条件查询

1.数据库结构

JDBC实现按条件查询_第1张图片

2.Java工程结构

JDBC实现按条件查询_第2张图片

3.代码

DBUtil.java

package com.mysql.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {

	public Connection getConn(){
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test";
		String username = "root";
		String password = "123456";
		Connection conn = null;
		
		try {
			Class.forName(driver);
			conn = (Connection) DriverManager.getConnection(url,username,password);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		return conn;
		
	}
}

Select.java

package com.mysql.jdbc;

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

public class Select {

	public void select(int id){
		String sql = "select * from content where id = ?";
		DBUtil db = new DBUtil();
		PreparedStatement pst = null;
		ResultSet rs = null;
		Connection conn = db.getConn();
		try {
			pst = conn.prepareStatement(sql);
			pst.setInt(1, id);
			rs = pst.executeQuery();
			while(rs.next()){
				System.out.println(rs.getString("id"));
				System.out.println(rs.getString("name"));
				System.out.println(rs.getString("content"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

测试类Main.java

package com.mysql.jdbc;


public class Main {

	public static void main(String args[]){
		Select select = new Select();
		select.select(2);
	}
}

4.输出结果

JDBC实现按条件查询_第3张图片

你可能感兴趣的:(数据库,JAVA)