java 数据库程序设计 学习笔记

1.为了避免重新输入整条指令,可以把指令保存到test.sql,然后source test.sql来运行该脚本文件

2.create table Course(…………);

drop table Course;



3.Driver,Connection,Statement,ResultSet

使用Driver接口加载到一个合适的驱动程序,使用Connection接口连接到数据库,使用Statement接口创建和执行sql语句,如果语句返回结果的话,使用ResultSet接口处理结果

import java.sql.*;

/*
 * 数据库辅助类
 */
public class DBOperation {

	private static final String DBDRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/coursesystem?user=root&password=admin";
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;

	public DBOperation() throws Exception {
		// 连接
		Class.forName(DBDRIVER);
		conn = DriverManager.getConnection(URL);
		stmt = conn.createStatement();
	}

	// 查询
	public ResultSet Query(String sql) {
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
		}
		return rs;
	}

	// 更新、删除

	public void TheAll(String sql) {
		try {
			stmt.executeUpdate(sql);
		} catch (SQLException e) {
		}
	}

	/**
	 * 关闭数据库链接模块
	 */
	public void CloseAll() {
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException ac) {
			ac.printStackTrace();
		}
	}

	/**
	 * 获取记录集总数模块
	 */
	public int getTotalRow(String sql) throws Exception {// 获取记录集总数
		DBOperation dbo = new DBOperation();
		ResultSet rsline = dbo.Query(sql);
		int i = 0;
		try {
			while (rsline.next()) {
				i++;
			}
			dbo.CloseAll();
		} catch (Exception er) {
		}
		return i;
	}

	/**
	 * 获取主键最大值,然后加“1”模块
	 */
	public String getMax(String table, String IDItem) throws Exception {
		// 生成根据ID项从高到底排序的查询语句
		DBOperation dbo = new DBOperation();
		String sql = "select  " + IDItem + "   from   " + table
				+ "   order   by   " + IDItem + "   desc";
		String id, i = null;
		try {
			// 得到结果集
			ResultSet rs = dbo.Query(sql);
			if (rs.next()) {
				// 如果数据库非空,得到第一条记录,也就是ID值最大的记录
				id = rs.getString(IDItem);
				// ID值增加1,得到新ID值
				i = (Integer.parseInt(id) + 1) + "";
			}
			/*
			 * 根据表,自动判断插入的初始值
			 */
			else {
				if (table == "Student") {
					i = "10000";
				} else if (table == "Teacher") {
					i = "1000";
				} else if (table == "Course") {
					i = "100";
				}
			}
			dbo.CloseAll();
		} catch (Exception e) {
		}
		return i;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值