Home  >  Article  >  Java  >  How to connect to database in Java

How to connect to database in Java

(*-*)浩
(*-*)浩Original
2019-05-05 16:48:2244632browse

How to connect Java to MySQL database: first download and decompress the jar library file, and import the library file into the corresponding project; then add JDBC; then create tables and add data in the Mysql database ;Finally connect to the database and read the data.

How to connect to database in Java

Java requires a driver package to connect to the MySQL database. The latest version download address is: http://dev.mysql.com/downloads/connector/j/, unzip it Finally, get the jar library file, and then import the library file in the corresponding project.

Create a program that uses JDBC to connect to the database. Specific steps:

##1. Load the driver:

Import the database connection jar package, create a lib folder in the project directory, and place the downloaded JDBC in the folder, as shown in the following figure:

How to connect to database in Java

2. Add JDBC:

Right-click the project name, select Add JARs... in the Libraries tab in the java build path, and select the JDBC just added, as shown below:

How to connect to database in Java

3. Create tables and add data in the Mysql database.

CREATE TABLE emp(
   empno            INT(4)          PRIMARY KEY,
   ename            VARCHAR(10),
   job              VARCHAR(9),
   hiredate         DATE,
   sal              FLOAT(7,2)
) ;

How to connect to database in Java

4. Connect to the database and read data:

Database name: sqltestdb

Packet name: emp

Port number: 3306

Username: root

Password: root

package sqldemo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class main {

    public static void main(String[] args) {
        //声明Connection对象
        Connection con;
        //驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        //URL指向要访问的数据库名mydata
        String url = "jdbc:mysql://localhost:3306/sqltestdb";
        //MySQL配置时的用户名
        String user = "root";
        //MySQL配置时的密码
        String password = "123456";
        //遍历查询结果集
        try {
            //加载驱动程序
            Class.forName(driver);
            //1.getConnection()方法,连接MySQL数据库!!
            con = DriverManager.getConnection(url,user,password);
            if(!con.isClosed())
                System.out.println("Succeeded connecting to the Database!");
            //2.创建statement类对象,用来执行SQL语句!!
            Statement statement = con.createStatement();
            //要执行的SQL语句
            String sql = "select * from emp";
            //3.ResultSet类,用来存放获取的结果集!!
            ResultSet rs = statement.executeQuery(sql);
            System.out.println("-----------------");
            System.out.println("执行结果如下所示:");  
            System.out.println("-----------------");  
            System.out.println("姓名" + "\t" + "职称");  
            System.out.println("-----------------");  
             
            String job = null;
            String id = null;
            while(rs.next()){
                //获取stuname这列数据
                job = rs.getString("job");
                //获取stuid这列数据
                id = rs.getString("ename");

                //输出结果
                System.out.println(id + "\t" + job);
            }
            rs.close();
            con.close();
        } catch(ClassNotFoundException e) {   
            //数据库驱动类异常处理
            System.out.println("Sorry,can`t find the Driver!");   
            e.printStackTrace();   
            } catch(SQLException e) {
            //数据库连接失败异常处理
            e.printStackTrace();  
            }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            System.out.println("数据库数据成功获取!!");
        }
    }

}

The above is the detailed content of How to connect to database in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn