java - 如何使用 JDBC 连接到本地主机?

标签 java mysql jdbc

我在自己的机器上安装了 MySql。我使用 MySql CommandLine Client 创建了数据库,创建了表,...在学校做项目时,我使用以下语法连接到学校的数据库:

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

最好的问候,

最佳答案

简单连接:

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

关于java - 如何使用 JDBC 连接到本地主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4436146/

相关文章:

Java:为什么接口(interface)中的声明不够?

java - Eclipse RCP - 将子菜单添加到现有文件菜单

MYSQL : How to create trigger from store procedure

php - 如何防止 PHP 中的 SQL 注入(inject)?

java - Apereo CAS 4.1.0-使用INVALID_TICKET消息的Gradle构建失败

java - 导入com.example无法解析

mysql 夏令时 - 判断 true 或 false

java - 如何在 while 循环中正确处理 Connection、ResultSet 和 Statement 对象

java jdbc 和 jframe

java - Sun JDBC ODBC 驱动程序或 MSSQL JDBC 驱动程序