⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 doupdatetest.java

📁 编程之道--java程序设计入门源代码
💻 JAVA
字号:
/**
 * 通过这个程序,向读者展示比较完整的JDBC数据库操作的顺序,
 * 在这个例子中主要展示数据库事务的处理与控制
 */

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet; 
import java.sql.DriverManager;
import java.sql.Date;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

public class DoUpdateTest
{
	
	private String url;//数据库URL
	private String userName;//登录数据库用户名
	private String password;//用户密码
	
	public static void main(String[] args)
	{		
		DoUpdateTest test = new DoUpdateTest();
		test.getProperty();		
		test.doUpdate();		
	}
	
	public void doUpdate()
	{
		try
		{
			Connection con = DriverManager.getConnection(url, userName, password);
			con.setAutoCommit(false);
			Statement st = con.createStatement();
			System.out.println("查询插入前的记录:");
			this.getStudent(st);
			String sql = "insert into student values('张丽','20021023','1978-6-10', '英语','山东')";
			st.executeUpdate(sql);
			System.out.println("\n查询插入后的记录:");
			this.getStudent(st);
			System.out.println("\n现在数据库进行回滚后,查询数据库结果:");
			con.rollback();
			this.getStudent(st);
			con.commit();
			System.out.println("\n再插入刚才的记录,事务提交后数据库查询的结果:");
			sql = "insert into student values('张丽','20021023','1978-6-10', '英语','山东')";
			st.executeUpdate(sql);
			con.commit();
			this.getStudent(st);
			System.out.println("\n现在数据再回滚,查询数据训结果:");
			con.rollback();
			this.getStudent(st);
			con.setAutoCommit(true);
					
			st.close();
			con.close();
				
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 从表中查询出所有记录
	 */
	public void getStudent(Statement st)
	{
		try
		{
			String sql = "select * from student";
			ResultSet rs = st.executeQuery(sql);
			
			while(rs.next())
			{
				String name =rs.getString("姓名");
				String number = rs.getString("学号");
				Date date = rs.getDate("出生日期");
				String spe = rs.getString("专业");
				String address = rs.getString("籍贯");
				
				System.out.println( "\n姓名:" + name + "\t学号:" + number + 
									"\t出生日期:" + date + "\t专业:" +
									spe + "\t籍贯:" + address ); 				
			}
			
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 读取属性配置文件
	 */
	public void getProperty()
	{
		Properties prop = new Properties();
		try
		{
			FileInputStream in = new FileInputStream("Driver.properties");
			prop.load(in);
	
			String driver = prop.getProperty("drivers");
			if(driver != null)
				System.setProperty("jdbc.drivers", driver);
			url = prop.getProperty("url");
			userName = prop.getProperty("user");
			password = prop.getProperty("password");			
		}
		catch(FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -