一般的な手順Javaの接続のmysql

1.まず、MySQLは、コンピュータにインストールされ
、その後、開発プロジェクトにjarファイルのパッケージをインポートすることは2.
3.呼び出して、適切なクラスコードを呼び出します。

例:
事前ににmysqlのJDBCという名前のデータベース作成
と呼ばれるユーザテーブルの確立を:

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 |
+----+------+----------+-------------+------------+

その後、ウェブは、接続されているEclipseのMySQLは次のとおりです。
まず、WebContentのジャービルド・パスに、次に右ビルド・パスとパケット選択アドオンにパケットをコピーします。
次に、以下のコードを記述します。

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;
			
	}
		
	}
}

}

それが正常にインタビューを実行します。

公開された35元の記事 ウォンの賞賛0 ビュー1280

おすすめ

転載: blog.csdn.net/c1776167012/article/details/104815125