Home > Database > Mysql Tutorial > body text

连接数据库模版

WBOY
Release: 2016-06-07 15:28:45
Original
1068 people have browsed it

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();
		}
	}
}
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!