Java | 实现读文件,写DB2数据库,多线程 | 解决线程名以及DB2 driver ClassNotFoundException的问题

这篇博客记录了作者在学习Java时进行的多线程、文件读取和DB2数据库连接的实践。在多线程中遇到线程命名问题,以及解决DB2数据库驱动ClassNotFoundException的方法。内容包括创建数据表的DDL,从文件读取数据并写入数据库的代码示例,以及针对线程名和DB2连接问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看了一遍Java语法,开始动手做一些练习, 主要集中在多线程,读文件,写数据这几个方面。

在研究多线程的过程中,碰到了线程名字的问题,做了一点研究。

而在连接DB2的时候,又碰到了ClassNotFoundException 找不到driver的问题,也找到了解决方案。


创建数据表的DDL:

create database TEST automatic storage yes;

create table customers(name varchar(20), age integer, location varchar(20));

连接数据库,并写数据库:

test.DB2Conn.java

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DB2Conn {
	private static Connection conn = null;
	private static PreparedStatement stmt = null;
	
	private static String url = "jdbc:db2://localhost:50000/TEST";
	private static String user = "ADMIN";
	private static String pwd = "test";
	
	public DB2Conn() {
		// TODO Auto-generated constructor stub
		try{
			System.out.println("Start to connecting DB2 database...");
			Class.forName("com.ibm.db2.jcc.DB2Driver"); //load DB driver
			
			conn = DriverManager.getConnection(url, user, pwd);
			System.out.println("Connet to DB2 database successfully.");	
			
		}catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
	 
	/**   
	 * Insert data
	 */
	    public void insert(String[] fields, String sql){  
	        try{  
	        stmt = conn.prepareStatement(sql);
	        stmt.setString(1,fields[0]);  
	        stmt.setInt(2, Integer.parseInt(fields[1]));
	        stmt.setString(3,fields[2]);  
	        int record = stmt.executeUpdate();
	        System.out.println("Insert " + record + " records successfully.");
	      }  
	     catch(SQLException e){  
	        System.out.println(e);  
	        }  
	        }  

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String sql = "insert into ADMIN.CUSTOMERS (name, age, location) values (?,?,?)";
		DB2Conn a = new DB2Conn();
		try{
			String[] record = {"Lucy","20","Beijing"};
			a.insert(record, sql);
			conn.close();
			System.out.println("Disconnet to DB2 database successfully.");
		}catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

}

从文件中读取数据,并写到数据库:

test.GetData.java

package test;

import java.io.RandomAccessFile;
import test.DB2Conn;

public class GetData {
    public static final String openFileStyle = "r";
    String path = null;
    DB2Conn conn = new DB2Conn();
    
	public GetData(String filePath) {
		// TODO Auto-generated constructor stub
		path = filePath;
	}
	
	/**
	 * Load file
	 */
	public void loadFile(){
		try{
			RandomAccessFile raf = new RandomAccessFile(path, openFileStyle);
			String line_record = raf.readLine(); //Read the first line.
			while(line_record != null){
				String[] fields = this.parseFile(line_record);
				String sql = "insert into ADMIN.CUSTOMERS (name, age, location) values (?,?,?)";
				conn.insert(fields, sql);
				line_record = raf.readLine(); //Read the next line.
			}
		}catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * Parse file
	 */
	public String[] parseFile(String line_record){
		String[] fields = line_record.split(",");
		return fields;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GetData gd = new GetData("c://test//test_read_file.txt");
		gd.loadFile();
	}
	
}

多线程实现从多个文件读取数据并写到数据库:

test.ThreadDemo.java

package test;

import test.GetData;

//class RunnableDemo implements Runnable {
class ThreadDemo extends Thread {
	private String threadName;
	GetData gd = null;
	String file = null;
	
	ThreadDemo(String name, String filePath) {
		threadName = name;
		System.out.println("Creating thread: " + threadName);
		
		file = filePath;
	}
	
	public void run() {
		System.out.println("Get main thread name: " + threadName);
		gd = new GetData(file);
		gd.loadFile();
		
	}
	
	public static void main(String args[]) {
		
		ThreadDemo R1 = new ThreadDemo("Thread-1", "c://test//test_read_file_1.txt");
	    R1.start();

	    ThreadDemo R2 = new ThreadDemo("Thread-2", "c://test//test_read_file_2.txt");
	    R2.start();	      
	   }
}


===========================================================================

在练习的过程中碰到的关于线程名的问题:

示例1

package test;

class ThreadDemo1 extends Thread {
	private String threadName;
	
	ThreadDemo1(String name) {
		threadName = Thread.currentThread().getName(); //重点看这里
		System.out.println("Creating thread: " + threadName);
	}
	
	public void run() {
		System.out.println("Get main thread name: " + threadName);
		printMsg();
	}
	
	public void printMsg(){
		String name=Thread.currentThread().getName();
		System.out.println("Get current thread name: " + name);
	}
	
	public static void main(String args[]) {
		
		ThreadDemo1 R1 = new ThreadDemo1("Thread-1");
	    R1.start();

	    ThreadDemo1 R2 = new ThreadDemo1("Thread-2");
	    R2.start();	      
	   }
}

结果:
Creating thread: main
Creating thread: main
Get main thread name: main
Get current thread name: Thread-5
Get main thread name: main
Get current thread name: Thread-6

示例2:
package test;

class ThreadDemo1 extends Thread {
	private String threadName;
	
	ThreadDemo1(String name) {
		threadName = this.getName(); //重点看这里
		System.out.println("Creating thread: " + threadName);
	}
	
	public void run() {
		System.out.println("Get main thread name: " + threadName);
		printMsg();
	}
	
	public void printMsg(){
		String name=Thread.currentThread().getName();
		System.out.println("Get current thread name: " + name);
	}
	
	public static void main(String args[]) {
		
		ThreadDemo1 R1 = new ThreadDemo1("Thread-1");
	    R1.start();

	    ThreadDemo1 R2 = new ThreadDemo1("Thread-2");
	    R2.start();	      
	   }
}

结果:
Creating thread: Thread-5
Creating thread: Thread-6
Get main thread name: Thread-5
Get current thread name: Thread-5
Get main thread name: Thread-6
Get current thread name: Thread-6

示例3:
package test;

class ThreadDemo1 extends Thread {
	private String threadName;
	
	ThreadDemo1(String name) {
		threadName = name; //重点看这里
		System.out.println("Creating thread: " + threadName);
	}
	
	public void run() {
		System.out.println("Get main thread name: " + threadName);
		printMsg();
	}
	
	public void printMsg(){
		String name=Thread.currentThread().getName();
		System.out.println("Get current thread name: " + name);
	}
	
	public static void main(String args[]) {
		
		ThreadDemo1 R1 = new ThreadDemo1("Thread-1");
	    R1.start();

	    ThreadDemo1 R2 = new ThreadDemo1("Thread-2");
	    R2.start();	      
	   }
}
结果:
Creating thread: Thread-1
Creating thread: Thread-2
Get main thread name: Thread-1
Get current thread name: Thread-5
Get main thread name: Thread-2
Get current thread name: Thread-6

示例1: threadName = Thread.currentThread().getName();
首先要明白, Thread.currentThread().getName()是获得调用这个方法的线程的名字, 也就是说,main线程中调用就是main, 子线程调用就是子线程。
所以:
1. 在实例化ThreadDemo 对象的时候,子线程并没有启动,这时候currentThread()得到的是主线程,也就是main,所以返回的就是main
2. 而在调用Thread类的方法start()之后,子线程才真正被启动,这时候currentThread()返回的就是对应的子线程, 它会按照子线程的的命名规则("Thread-" + createCount)返回thread的名字

示例2: threadName = this.getName();
this.getName()这个方法是获取当前ThreadDemo对象的名字,也就是子线程的名字

示例3: threadName = name;
直接使用实例化的时候传进来的名字

Best practice: create class to implement Runnable, instead of extends Thread.


==================================================================

在练习的过程中碰到的关于DB2 driver ClassNotFoundException的问题:

Java连接DB2数据库, 如果碰到ClassNotFoundException, 如下:
java.lang.ClassNotFoundException: com.ibm.db2.jdbc.app.DB2Driver
1. 检查driver是否在build path存在
2. 检查driver是否正确,具体如下:
Driver name is depends on the driver we are using.
Use COM.ibm.db2.jdbc.app.DB2Drive when db2java.zip is in your path.
Use com.ibm.db2.jcc.DB2Driver when db2jcc.jar & db2jcc_license_cu.jar are in your classpath.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值