Easily complete java database operation, must-see series white

Today to talk about the java connection with the operation of the JDBC driver to connect to the database. This article takes only five minutes can finish up in.

First, a new package lib in our code block, FIG.

Here Insert Picture Description

Then download the corresponding mysql database-driven, in general, because I use the MySQL database version, database-driven corresponding number 5.7 is 5.1.46, as my next good database, if you download the corresponding database-driven, official website a more detailed version of the match, so the download time to remember under the corresponding on it.

Here Insert Picture Description

The drive to copy the package inside our lib

Here Insert Picture Description

Then tap and hold to copy the mysql-connector-java-5.1.46.jar, right, build path

Then it points add to build path, so that the later described FIG becomes successful driving added

Here Insert Picture Description

And then copy the following code to your program inside, you have won. Of course, you need to pay attention to is that you have to be built in the mysql database, such as database name me the following code is nz2001, the name of the database to write your own, you have that into your own. The following code, I want to connect to the database is nz2001, the database user name is root, password is 123456, and then you also need to have their own data table, for example, I want to connect the table below is a person, the code does my job is to insert the user name and password

package com.qianfeng.ps.am.first;
/*
 * 1: 使用jdbc,完成对数据库的DML操作; 向user表插入一条纪录,添加一条纪录,删除一条纪录;
 * 
 * 
 * */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DemoInser {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://127.0.0.1:3306/nz2001"; //连接哪个数据库 ip:端口/数据库名字;
			String name = "root"; //你的数据库连接的用户名
			String pass = "123456";//你的数据库连接的密码
			//DriverManager.getConnection通过一个静态方法,获取一个和数据库的连接;
			Connection connection = DriverManager.getConnection(url, name, pass);
			
			System.out.println("获取连接成功");
			Statement stm = connection.createStatement();
			
			System.out.println("获取操作数据库的对象成功");
			String sql = "INSERT INTO person(pname,psex) VALUES('panshuo',3),('ffff',3)";
			int result = stm.executeUpdate(sql); //操作数据库的增删改 DML 语句
			if(result > 0) {
				System.out.println("插入数据成功");
				
			}
			stm.close(); //操作数据库的对象要关闭
			connection.close(); // 数据库连接要关闭
			
			System.out.println("关闭连接成功");
			
		}catch(Exception e){
			
			
			e.printStackTrace();
		}
	}

}

Published 32 original articles · won praise 9 · views 3126

Guess you like

Origin blog.csdn.net/weixin_43501566/article/details/105107981
Recommended