您的位置:首页 > 数据库 > MySQL

mysql jdbc连接

2013-01-04 20:13 162 查看
package com.mayi.jdbc.util;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;

public class Jdbc_Util {
	private Connection conn =null;
	private Statement statement =null;
	private ResultSet result=null;
	private boolean b;
	private int a;
	
	public Jdbc_Util(){
		try {
			Class.forName("com.mysql.jdbc.Driver");//加载驱动

			conn = (Connection) DriverManager.getConnection(
						"jdbc:mysql://localhost:3306/test", 
						"mayi", "123456");//获得连接
				
			System.out.println("加载驱动成功!!");
		} catch (ClassNotFoundException e) {
			System.out.println("加载驱动失败!!");
			e.printStackTrace();
		}catch (SQLException e) {
			System.out.println("获取数据库连接失败!!");
			e.printStackTrace();
		}
	}
	//增加数据
	public int add(String sql){
		try {
			statement =conn.createStatement();
			a=statement.executeUpdate(sql);		
		} catch (SQLException e) {		
 		 e.printStackTrace();
		}
		return a;
	}

	//删除数据
	public int delete(String sql){
		try {
			statement =conn.createStatement();
			a=statement.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return a;
	}
	
	//查询数据
	public ResultSet select(String sql){
		try {
			Statement statement =conn.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
			result=statement.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;		
	}
	
	//改数据
	public int update(String sql){
		try {
			statement =conn.createStatement();
			a=statement.executeUpdate(sql);		
		} catch (SQLException e) {		
 		 e.printStackTrace();
		}
		return a;
	}
	
	//关闭资源
	public boolean close(){
		try {
			result.close();
			statement.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
}


mysql-connector-java-5.1.20-bin.jar 驱动包在我下载的mysql安装文件里自己带了一个,要是没有,也可以在这里下载:jdbc

mysql下载地址:mysql
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: