Eclipse接続データベース(基本)

ステップ 1: jar パッケージをダウンロードする

ステップ 2: jar パッケージをインポートする

プロジェクト名を右クリックし、「プロパティ」をクリックします。

図に示すように、「追加」をクリックした後、ダウンロードしたばかりの jar パッケージを見つけて追加し、「適用」をクリックして閉じると、追加が成功した後のプロジェクト ディレクトリが図に示されています。

 ステップ 3: データベースに接続する

 データベースを作成し、その中に従業員テーブルを作成します。

通常プログラムを作成するのと同じように、パッケージとクラスを作成します。ここでは、データベース接続パッケージを構築し、その中に Example クラスを作成しました。

 接続コードを記述してドライバーをロードします。

try
		{ 
			Class.forName("com.mysql.cj.jdbc.Driver");   //加载MYSQL JDBC驱动程序  
			//Class.forName("org.gjt.mm.mysql.Driver"); 
			System.out.println("成功加载Mysql驱动程序!"); 
		 } 
		catch (Exception e) 
		{
			System.out.print("加载Mysql驱动程序时出错!"); 
		    e.printStackTrace(); 
		}

 データベースに接続します。データベース名は db001、ログイン名は root、パスワードは自分で設定したデータベース パスワードです。

try 
		{ 
			Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/db001","root","自己的数据库密码");
			//连接URL为  jdbc:mysql//服务器地址/数据库名,后面的2个参数分别是登陆用户名和密码 
			System.out.println("成功连接Mysql服务器!");
			Statement stmt = connect.createStatement(); 
			ResultSet rs = stmt.executeQuery("select * from employee where age>25");
		    while (rs.next())
			 { 
				 System.out.println(rs.getString("name")); 
		     }
		    connect.close();
         } 
		catch (Exception e) 
		{ 
			System.out.print("获取数据错误!");
			e.printStackTrace(); 
		}

完全なコード: 

package 数据库连接;

import java.sql.*; 

public class Example {
	public static void main(String args[]) 
	{
		try
		{ 
			Class.forName("com.mysql.cj.jdbc.Driver");   //加载MYSQL JDBC驱动程序  
			//Class.forName("org.gjt.mm.mysql.Driver"); 
			System.out.println("成功加载Mysql驱动程序!"); 
		 } 
		catch (Exception e) 
		{
			System.out.print("加载Mysql驱动程序时出错!"); 
		    e.printStackTrace(); 
		}
		try 
		{ 
			Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/db001","root","你设置的密码");
			//连接URL为  jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码 
			System.out.println("成功连接Mysql服务器!");
			Statement stmt = connect.createStatement(); 
			ResultSet rs = stmt.executeQuery("select * from employee where age>25");  //输出表中年纪大于25的员工 
		    while (rs.next())
			 { 
				 System.out.println(rs.getString("name")); 
		     }
		    connect.close();
         } 
		catch (Exception e) 
		{ 
			System.out.print("获取数据错误!");
			e.printStackTrace(); 
		}
	}
	
	
}

操作結果:

 

おすすめ

転載: blog.csdn.net/weixin_47817212/article/details/128789918