Eclipse connection database (basic)

Step 1: Download the jar package

Step 2: Import the jar package

Right-click the project name, click properties;

As shown in the figure, after clicking add, find the jar package just downloaded and add it, click apply and close, and the project directory after the addition is successful is shown in the figure;

 Step 3: Connect to the database

 Create a database and create an employee table in it;

Create packages and classes like you usually write programs. Here I built a database connection package and created an Example class in it;

 Write the connection code and load the driver;

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

 Connect to the database, where the database name is db001, the login name is root, and the password is the database password set by yourself.

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

Full code: 

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

operation result:

 

Guess you like

Origin blog.csdn.net/weixin_47817212/article/details/128789918