1. 程式人生 > >JAVA連線MySQL資料庫

JAVA連線MySQL資料庫

package com.coding.test;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class MyDemo {
	public static void main(String[] args) {
		try {
			//載入資料庫驅動
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("載入成功!");
		} catch (ClassNotFoundException e) {
			System.out.println("載入失敗!未找到載入資料庫驅動!");
			e.printStackTrace();
		}
		String url = "jdbc:mysql://localhost:3306/test";//資料庫地址及資料庫名
		String user = "root";							//賬戶
		String password = "root";						//資料庫密碼
		Connection connection;
		Statement statement;
		try {
			connection = (Connection) DriverManager.getConnection(url, user, password);//獲取連線
			statement = (Statement) connection.createStatement();
			String sql = "select * from store";	//建立SQL語句
			ResultSet set = statement.executeQuery(sql);	//執行SQL語句,返回結果集
			//判斷是否查詢成功
			if (!(set.equals(null))) {
				System.out.println("連線成功!");
			} else {
				System.out.println("連線失敗!");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
}