2010-12-14 54 views
3

我在我自己的機器上安裝了MySql。我創建了數據庫,創建表,...使用MySql CommandLine Client。在學校的一個項目工作時,我使用此語法連接到學校數據庫:如何使用JDBC連接到本地主機?

public static Statement connect() { 
    try { 
    Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    conn = DriverManager.getConnection("1", "2", "3"); 
    stmt = conn.createStatement(); 
    } 
    catch(Exception e) { 
    System.out.println("Connection Error: " + e); 
    } 
    return stmt; 
} 

在我的本地機器,我就不必輸入用戶名,我所做的只是用我的密碼登錄root用戶:

Enter password: **** 
Welcome to the MySQL monitor. Commands end with ; or \g. 
Your MySQL connection id is 1 
Server version: 5.1.53-community MySQL Community Server (GPL) 

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. 
This software comes with ABSOLUTELY NO WARRANTY. This is free software, 
and you are welcome to modify and redistribute it under the GPL v2 license 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. 

mysql> use chandb; 
Database changed 
mysql> show tables; 
+------------------+ 
| Tables_in_chandb | 
+------------------+ 
| another   | 
| cars    | 
| employees  | 
+------------------+ 
3 rows in set (0.03 sec) 

mysql> select * from Another; 
+----+-----------+----------+ 
| Id | GoldValue | Model | 
+----+-----------+----------+ 
| 0 |  100 | Civic DX | 
+----+-----------+----------+ 
1 row in set (0.00 sec) 

mysql> 

我想知道如何連接到本地機器的數據庫?我應該把作爲參數的方法.getConnection內

conn = DriverManager.getConnection( 
    "1", // ? 
    "2", // ? 
    "3" ); // ? 

最好的問候,

+3

夥計,從您的代碼段刪除用戶名和密碼,儘快!當你處於這個狀態時,也要刪除主機名。你也不需要在錯誤的'show tables'中輸入代碼片段 – Todd 2010-12-14 05:33:03

+0

感謝提醒安全問題。 Editted。 – Chan 2010-12-14 06:00:33

回答

6

簡單連接:

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

public class Main { 
    public static void main(String[] argv) throws Exception { 
    String driverName = "org.gjt.mm.mysql.Driver"; 
    Class.forName(driverName); 

    String serverName = "localhost"; 
    String mydatabase = "mydatabase"; 
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase; 

    String username = "username"; 
    String password = "password"; 
    Connection connection = DriverManager.getConnection(url, username, password); 
    } 
} 
+0

感謝穆罕默德,但它沒有奏效。我得到了主要的異常。異常在線程「主」java.sql.SQLException:找不到合適的驅動程序jdbc:mysql:// localhost/chandb \t at java.sql.DriverManager.getConnection(未知來源) \t at java.sql.DriverManager.getConnection (未知來源) \t在Program.main(Program.java:15) – Chan 2010-12-14 05:58:15

+0

我得到它的工作;)謝謝;) – Chan 2010-12-14 06:05:24

+0

URL中有空格,使它無效。去掉它。 – BalusC 2011-01-23 13:54:32

2

看起來你離開你的用戶名和密碼您發佈的來源。

我不明白爲什麼你不能只是做

DriverManager.getConnection("jdbc:mysql://localhost/chandb", "user, "pass");