连接数据库模版

WBOY
發布: 2016-06-07 15:28:45
原創
1068 人瀏覽過

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();
		}
	}
}
登入後複製

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!