【问题标题】:How to connect to local host using JDBC?如何使用 JDBC 连接到本地主机?
【发布时间】:2010-12-14 05:23:33
【问题描述】:

我在自己的机器上安装了 MySql。我使用 MySql 命令行客户端创建了数据库、创建表等。在学校做项目时,我使用以下语法连接到学校的数据库:

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"  ); // ?

最好的问候,

【问题讨论】:

  • 老兄,尽快从您的代码 sn-p 中删除该用户名和密码!当你在它的时候,也删除主机名。此外,您不需要用错误输入的show tables 位来混淆 sn-p
  • 感谢您提醒安全问题。已编辑。

标签: java mysql jdbc


【解决方案1】:

简单连接:

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);
  }
}

【讨论】:

  • 感谢 Mohamed,但它不起作用。我在main中抛出异常。 java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) 中的线程“main”java.sql.SQLException:找不到适合 jdbc:mysql://localhost/chandb 的驱动程序在 Program.main(Program.java:15)
  • 网址中有空格,导致无效。删除它。
【解决方案2】:

您的用户名和密码似乎留在了您发布的来源中。

我不明白为什么你不能这样做

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

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2013-01-24
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多