java通过JDBC对数据库进行查询

  • Post author:
  • Post category:java


先下载一个jar包,导入项目中。

下载链接:

https://dev.mysql.com/downloads/connector/j/

导入项目中,如下

右击之后出现Build path选择,再点击Add to Build Path就创建好了。


创建JDBC进行数据库的操作主要为六个步骤:

* 1.注册驱动 DriverManager

* 2.获取数据库的连接connection

* 3.获取传输器

* 4.执行SQL语句

* 5.遍历结果集

* 6.释放资源

package cn.tedu.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

/**
 * 对数据库数据表进行查询
 */
public class JDBCTest01 {

	public static void main(String[] args) {
		Connection co = null;
		Statement st = null;
		ResultSet re = null;
		try {
			//注册驱动
			Class.forName("com.mysql.jdbc.Driver");
			//获取连接
			co = DriverManager.getConnection("jdbc:mysql://localhost:3306/jt_yh", "root", "root");
			//sql语句
			String sql = "select * from tb_order";
			//获取传输
			st = co.createStatement();
			//执行sql
			re = st.executeQuery(sql);
			//输出结果
			System.out.println("id"+"\t"+"door_id"+"\t"+"order_no"+"\t"+"order_type"+"\t"+"person_num"+"\t"+"cashier"+"\t"+"create_time"+"\t"
					+"end_time"+"\t"+"payment"+"\t"+"payment_type"+"\t"+"print_time");
			//遍历结果集
			while(re.next()) {
				int id = re.getInt("id");
				int door_id = re.getInt("door_id");
				String order_no = re.getString("order_no");
				String order_type = re.getString("order_type");
				int person_num = re.getInt("person_num");
				String cashier = re.getString("cashier");
				Timestamp create_time = re.getTimestamp("create_time");
				Timestamp end_time = re.getTimestamp("end_time");
				double payment = re.getDouble("payment");
				String payment_type = re.getString("payment_type");
				Timestamp print_time = re.getTimestamp("print_time");
				System.out.println(id+"\t"+door_id+"\t"+order_no+"\t"+order_type+"\t"+person_num+"\t"+cashier
						+"\t"+create_time+"\t"+end_time+"\t"+payment+"\t"+payment_type+"\t"+print_time);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(re!=null) {
				try {
					re.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(st!=null) {
				try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(co!=null) {
				try {
					co.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

执行结果:



版权声明:本文为qq_45572615原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。