Java: jdbc mysql database connection

To install the mysql eclipse and not go into details here.

1 must package the jar

To realize the database connection, first download the mysql-connector-java-5.1.47 (or other version) jar package. Low version of the jar package is not abnormal jet lag problem.

Recommend "Looking for previous GA versions?" On the right to download the download interface points lower version.

https://blog.csdn.net/weixin_44747284/article/details/88370421 I think that this tutorial.

 

2.mysql preparation

I was referring to rookie tutorial download mysql.

https://www.runoob.com/mysql/mysql-install.html

My computer is a windows system, then pay attention to before my.ini configuration file to build a large empty folder in the mysql data folder, if there begin with a data folder, the folder should be deleted everything .

If you follow the steps to complete the tutorial steps, you should have been completed. But there are also a variety of other issues that may arise, Baidu.

Operation with cmd: cmd to open an administrator to use. Open the database to be advanced to the bin directory. Here is entering the bin, open mysql, user login, and exit operations. After opening there will be a successful mysql> small flag.

 

cd C:\mysql-5.7.27-winx64\bin

net start mysql

mysql -uroot -p

exit

 

3.Java program

Open the mysql.

The first try, if loading fails will throw a ClassNotFoundException.

第二个try中:con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql?characterEncoding=UTF-8","root","");
这一行

jdbc:mysql://   是指JDBC连接方式;
127.0.0.1:       是指你的本机地址;
3306               SQL数据库的端口号;
mysql              就是你要连接的数据库的名字。

第二个双引号里是你的mysql数据库用户名,第三个双引号里是登录密码,我设成没有密码了,所以就空着。

 1 import java.sql.*;
 2 public class Conn {
 3     Connection con;
 4     public Connection getConnection() {
 5         try {
 6             Class.forName("com.mysql.jdbc.Driver");  System.out.println("数据库驱动加载成功");
 7         } catch(ClassNotFoundException e){
 8             e.printStackTrace();
 9         }
10         try {
11             con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql?characterEncoding=UTF-8","root","");
12             System.out.println("数据库连接成功");
13         } catch (SQLException e) {
14             e.printStackTrace();
15         }
16         return con;
17     }
18     public static void main(String[] args) {
19         Conn c = new Conn();
20         c.getConnection();
21     }
22 }

然后就运行成功了。

 

Guess you like

Origin www.cnblogs.com/qjqj0-0/p/11247712.html