>  기사  >  데이터 베이스  >  连接数据库模版

连接数据库模版

WBOY
WBOY원래의
2016-06-07 15:28:451047검색

package com.mingxin.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import com.mysql.jdbc.ResultSet;import com.mysql.jdbc.Statement;public class ConnectionUtils {private static String driver = com

package com.mingxin.util;

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

import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

public class ConnectionUtils {

	private static String driver = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://127.0.0.1:3306/db_mx";
	private static String user = "root";
	private static String password = "123456";
	private static Connection conn = null;
	
	static{
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			System.out.println("驱动加载失败..");
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection(){
		try {
			conn = DriverManager.getConnection(url, user, password);
			if(!conn.isClosed()){
				System.out.println("Successed connecting to the Database...");
			}
		} catch (SQLException e) {
			System.out.println("数据库连接失败...");
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void main(String[] args) {
//		getConnection();
		try {
			Statement statement = (Statement) conn.createStatement();
			String sql = "select * from user";
			ResultSet rs = (ResultSet) statement.executeQuery(sql);
			String email = null;
			String name = null;
			String phone = null;
			while(rs.next()){
				email = rs.getString("u_email");
				name = rs.getString("u_name");
				phone = rs.getString("u_phone");
				System.out.println("u_email=" + email + " ___u_name=" + name + " ____phone=" + phone);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.