简体   繁体   English

使用Java连接到MySQL数据库

[英]Connecting to a MySQL Database with Java

I want to connect to my MySQL database with Java. 我想用Java连接到我的MySQL数据库。

I am using JDBC and I have the driver installed. 我正在使用JDBC,并且已安装驱动程序。 (com.mysql.jdbc.Driver) (com.mysql.jdbc.Driver)

The only problem is that I keep getting an error: 唯一的问题是我不断收到错误消息:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException The last packet sent successfully to the server was 0 milliseconds ago. com.mysql.jdbc.exceptions.jdbc4.CommunicationsException成功发送到服务器的最后一个数据包是0毫秒前。

Here is my code: 这是我的代码:

Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:/mydomain.com/mydatabase", "username", "password");

I am not positive how to compose the URL (and where I get my username and password) but I have done A LOT of research. 我对如何撰写URL(以及在哪里获取用户名和密码)并不满意,但是我已经进行了大量研究。

I am the only person with acess to my database and domain, so there's no use asking the admin. 我是唯一访问我的数据库和域的人,因此询问管理员没有任何用处。

I use phpMyAdmin to create the database(s) and manage them. 我使用phpMyAdmin创建数据库并进行管理。 Do I use my phpMyAdmin username and password or what? 我使用phpMyAdmin用户名和密码还是什么?

By the way, my site is hosted on Yahoo! 顺便说一句,我的网站托管在Yahoo!上。 Small Business. 小本生意。

So my questions are: 所以我的问题是:

  • How do I make the connection URL? 如何建立连接网址?
  • What is my username and password? 我的用户名和密码是什么?

I would say you are missing a forward slash on your URL. 我想说的是您的网址缺少正斜杠。

Connection connection = DriverManager.getConnection("jdbc:mysql://mydomain.com/mydatabase", "username", "password");

Or I have a feeling that there is something wrong with your access privileges. 或者我觉得您的访问权限有问题。 This same thing happened to me also and it was a problem of Firewall blocking the port on the server. 我也发生了同样的事情,这是防火墙阻止服务器端口的问题。 So verify this is not the case. 因此,验证情况并非如此。

Load the drivers for mysql
 Class.forName("com.mysql.jdbc.Driver");
connect with the data base
 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/widget_corp","dbuser","dbpassword");               
.....jdbc:mysql://this is use as it is
.....127.0.0.1 this is the address of localhost You can use the word "localhost" insted of      "127.0.0.1"
.....dbuser is the data base user
.....dbpassword is the password of the dbuser
.....3306 is the default port used for database

How do I make the connection URL? 如何建立连接网址?

Are you missing a forward slash in your URL? 您是否在网址中缺少斜线? I would've assumed it would be something like: 我本来以为是这样的:

jdbc:mysql://server/database

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM