如何使用JDBC连接到本地主机? [英] How to connect to local host using JDBC?

查看:87
本文介绍了如何使用JDBC连接到本地主机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I installed MySql on my own machine. I created database, create table, ... using MySql CommandLine Client. When working on a project in school, I connected to school's database using this syntax:

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用户身份用密码登录即可.

In my local machine, I don't have to type in user name, all I did is just login with my password as root user:

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

I would like to know how can I connect to my local machine's database? what should I put as parameters within method .getConnection

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

最诚挚的问候,

Best regards,
Chan

推荐答案

简单连接:

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

这篇关于如何使用JDBC连接到本地主机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆