“註冊”操作:先判斷後添加入庫

一、RegisterService.java

package com.raisecom.server.qq2015.db;

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

public class RegisterService {
	Connection conn = DBPool.getConnection();
	PreparedStatement stm = null;

	private String username;
	private String userpass;

	public RegisterService(String username, String userpass) {
		this.username = username;
		this.userpass = userpass;
	}

	public boolean register() {
		if (conn != null) {
			try {
				stm = conn
						.prepareStatement("select * from userinfo where username=? ");
				stm.setString(1, username);

				// 如果該用戶名不存在,則註冊
				if (!stm.executeQuery().next()) {
					try {
						stm = conn
								.prepareStatement("insert into userinfo values(?,?)");
						stm.setString(1, username);
						stm.setString(2, userpass);

						if (stm.executeUpdate() == 1) {
							System.out.println("Register Success!");
							return true;
						}
					} catch (SQLException e) {
						e.printStackTrace();
					} finally {
						close();
					}

				} else {
					System.out.println("該用戶名存在");
					return false;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("connection error");
		return false;

	}
	

	public void close() {
		try {
			stm.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new RegisterService("00", "1").register();
	}

}



二、DBPool.java (數據庫連接池,derby數據庫+各種jar包 + c3p0.jar)

package com.raisecom.server.qq2015.db;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBPool {
	public static ComboPooledDataSource ds=new ComboPooledDataSource();
	
	static{
		try {
			ds.setDriverClass("org.apache.derby.jdbc.EmbeddedDriver");
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		
		ds.setJdbcUrl("jdbc:derby:userinfo;create=false");
		ds.setUser("abc");
		ds.setPassword("abc");
		ds.setMaxPoolSize(50);
		ds.setMinPoolSize(10);
		ds.setInitialPoolSize(10);
	}
	public static Connection getConnection(){
		
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章