JDBC first program

JDBC first program

1, first build a database

2, the database and Java projects connected to the

1. Build a database

Database: jdbcstudy

This database jdbcstudy There is a table: users

             

 

2. Java project database and connect

Results are as follows:

 

Below the code, the code can be used as a template connection to the database, only changes to 4 where indicated.

 

The complete code is as follows:

package com.wang.lesson;

import java.sql.*;

public class jdbcFirstDemo {
   public static void main(String[] args) throws ClassNotFoundException, SQLException {
       //step 1:加载驱动,下面这行是固定写法
       Class.forName("com.mysql.jdbc.Driver"); //固定写法
       //step 2:用户信息和url
       //下面三行也是固定写法,除了jdbcstudy这几个字符,这几个字符是数据库的名字。本项目连接的数据库名就是jdbcstudy
       String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
//除jdbcstudy,其他为固定写法.jdbcstudy是自己数据库的名字为非固定写法
        String username = "root";   //非固定写法,写自己的用户名,在下面的3.2具体说明中有截图
        String password = "123456"; //非固定写法,写自己的密码,在下面的3.2具体说明中有截图
       //step 3:用驱动管理类(DriverManager)去获得连接,下面这行是固定写法
       Connection connection = DriverManager.getConnection(url,username,password); //固定写法
       //step 4:下面这行是固定写法,得到了SQL的对象:statement
       Statement statement = connection.createStatement(); //固定写法
       //step 5:下面这行:SELECT * FROM users是SQL的语法,是获取我自己数据库中的users表单的全部信息
       String sql = "SELECT * FROM users";                 //非固定写法,双引号中的users是自己的数据库的表单名称
       ResultSet resultSet = statement.executeQuery(sql);  //固定写法,返回的结果集中,封装了全部的查询结果
       //step 6:输出查询结果看下
       while (resultSet.next()){
           System.out.println("id = " + resultSet.getObject("id"));
           System.out.println("name = " + resultSet.getObject("NAME"));
           System.out.println("pwd = " + resultSet.getObject("PASSWORD"));
           System.out.println("email = " + resultSet.getObject("email"));
           System.out.println("birth = " + resultSet.getObject("birthday"));
      }
       //step 6:释放连接
       resultSet.close();           //固定写法
       statement.close();           //固定写法
       connection.close();          //固定写法
  }
}

输出如下:

id = 1
name = zhansan
pwd = 123456
email = za@sina.com
birth = 1980-12-04
id = 2
name = lisi
pwd = 123456
email = lisi@sina.com
birth = 1981-12-04
id = 3
name = wangwu
pwd = 123456
email = wangwu@sina.com
birth = 1979-12-04

Process finished with exit code 0

3. 上述代码中,需要根据自己数据库修改的4(其中的2包含两个地方)个地方,具体说明

3.1 非固定写法1

step2中的:jdbcstudy,这个是我自己数据库的名字。

截图如下:

 

3.2 非固定写法2

step2中的:username 和 password,是我自己数据库的用用户名和密码。

截图如下:

 

3.2 非固定写法3

step3中的:users是我自己的数据库的表名。

截图如下:

 

 

 

 

Guess you like

Origin www.cnblogs.com/WZ-BeiHang/p/12381274.html