Java JDBC连接数据库 查询SELECT

package com.edu;
import java.sql.*;

public class jdbctest {

	public static void main(String[] args) throws SQLException, ClassNotFoundException {
			Class.forName("com.mysql.jdbc.Driver");
			String url="jdbc:mysql:///test";
			Connection conn=DriverManager.getConnection(url,"root","root");
			String sql="select name,age from users where id=?";
			PreparedStatement pstmt=conn.prepareStatement(sql);
			pstmt.setInt(1, 1);
			ResultSet rs=pstmt.executeQuery();
			while(rs.next()){
				String name=rs.getString(1);
				int age=rs.getInt("age");
				System.out.println(name+":"+age);
			}
			rs.close();
			pstmt.close();
			conn.close();
	}

}

注意: throws SQLException, ClassNotFoundException 抛出异常

猜你喜欢

转载自blog.csdn.net/bancroft_boy/article/details/81144416