General Procedure java connecting mysql

1. First mysql installed on a computer
and then importing the jar package in development projects 2.
3. call and calls the appropriate class code.

Example:
in advance creates a database named mysql jdbc in the
establishment of a called user table:

mysql> create database jdbc;
Query OK, 1 row affected (0.05 sec)

mysql> use jdbc
Database changed
mysql> create table users(
    -> id int primary key auto_increment,
    -> name varchar(40),
    -> password varchar(40),
    -> email varchar(60),
    -> birthday date)character set utf8 collate utf8_general_ci;
Query OK, 0 rows affected, 1 warning (0.11 sec)
mysql> insert into users(name,password,email,birthday)
    -> values('zs','123456','[email protected]','1980-12-03');
Query OK, 1 row affected (0.09 sec)
mysql> select * from users;
+----+------+----------+-------------+------------+
| id | name | password | email       | birthday   |
+----+------+----------+-------------+------------+
|  1 | zs   | 123456   | zs@sina.com | 1980-12-03 |
+----+------+----------+-------------+------------+

Then the web is connected eclipse mysql:
First, copy the packet into the WebContent jar, then right build path and packet selection add to build path.
Then write the following code:

package cn.itcast.jdbc.example;

import java.sql.*;
public class Example01 {
	
public static void main(String[] args) throws SQLException{
	Statement stmt=null;
	ResultSet rs=null;
	Connection conn=null;
	try{
		Class.forName("com.mysql.cj.jdbc.Driver");
		String url="jdbc:mysql://localhost:3306/jdbc?&useSSL=false&serverTimezone=UTC";
		String username="root";
		String password="root";
		conn = DriverManager.getConnection(url,username,password);
		stmt= conn.createStatement();
		String sql = "select * from users";
		rs = stmt.executeQuery(sql);
		System.out.println("id|name|password|email|birthday");
		
		while(rs.next())
		{
			int id = rs.getInt("id");
			String name = rs.getString("name");
			String psw = rs.getString("password");
			String email = rs.getString("email");
			Date birthday = rs.getDate("birthday");
			System.out.println(id +" | "+name+" | "+psw+" | "+email+" | "+birthday);
			
		}
	}catch(ClassNotFoundException e)
	{
		e.printStackTrace();
	}
	finally{
		if(rs!=null){
			try{
				rs.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
			rs=null;
		}
		
		if(stmt!=null){
			try{
				stmt.close();
			}
			catch(SQLException e)
			{
				e.printStackTrace();
			}stmt=null;
			
		}if(conn!=null){try{
			conn.close();
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
		conn=null;
			
	}
		
	}
}

}

Run it successfully interviewed.

Published 35 original articles · won praise 0 · Views 1280

Guess you like

Origin blog.csdn.net/c1776167012/article/details/104815125