2010-12-14 59 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");