Use of JDBC in JAVA

JDBC(Java Data Base Connectivity,Javadata base Connection) is a Java for executing SQL statements API, which provides unified access to multiple relational databases, is used by a set of Java Language Written class and interface composition. JDBC provides a benchmark against which more advanced tools and interfaces can be built to enable database developers to write database applications, and JDBC is also a trademark name.

Definition: With JDBC, it's easy to send SQL statements to various relational data. In other words, with the JDBC API, access is not necessary Sybase database Write a program specifically for access Oracle database Write another program, or write another program for accessing Informix database, etc. Programmers only need to use JDBC. It's enough for an API to write a program that can send SQL calls to the corresponding database. At the same time, the combination of Java language and JDBC enables programmers not to write different applications for different platforms, but to write programs once to run on any platform, which is also the advantage of Java language "write once, run everywhere".

JDBC is simply an API tool for JAVA to connect to databases. Specific can be done: establish a connection with the database, send statements to operate the database and process the results.

The following is a simple Java project for JDBC. We achieved it. Addition, deletion and alteration of the data of the human object.

The following is part of the code: (all of the code is below)

The database table design, file distribution and results are displayed in the files uploaded below.

Tools: API toolkits for myeclipse and JDBC. What I'm using here is

You can download it online.

Connect to the database:

Goddess.java

package com.imooc.model;

import java.util.Date;

public class Goddess {

	private Integer id;
	private String user_name;
	private Integer sex;
	private Integer age;
	private Date birthday;
	private String email;
	private String mobile;
	private String create_user;
	private String update_user;
	private Date create_date;
	private Date update_date;
	private Integer isdel;//sign
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	
	public String getUser_name() {
		return user_name;
	}
	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}
	public Integer getSex() {
		return sex;
	}
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getCreate_user() {
		return create_user;
	}
	public void setCreate_user(String create_user) {
		this.create_user = create_user;
	}
	public String getUpdate_user() {
		return update_user;
	}
	public void setUpdate_user(String update_user) {
		this.update_user = update_user;
	}
	public Date getCreate_date() {
		return create_date;
	}
	public void setCreate_date(Date create_date) {
		this.create_date = create_date;
	}
	public Date getUpdate_date() {
		return update_date;
	}
	public void setUpdate_date(Date update_date) {
		this.update_date = update_date;
	}
	public Integer getIsdel() {
		return isdel;
	}
	public void setIsdel(Integer isdel) {
		this.isdel = isdel;
	}
	@Override
	public String toString() {
		return "Goddess [id=" + id + ", user_name=" + user_name + ", sex=" + sex + ", age=" + age + ", birthday="
				+ birthday + ", email=" + email + ", mobile=" + mobile + ", create_user=" + create_user
				+ ", update_user=" + update_user + ", create_date=" + create_date + ", update_date=" + update_date
				+ ", isdel=" + isdel + "]";
	}
	

}
	JDBCTest.java
package com.imooc.db;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
public class JDBCTest {
	private static Connection conn =null;
	static{
		String url = "jdbc:mysql://localhost:3306/imooc";
		// Database username
		String username = "root";
		// Database password
		String password = "123456";
		try {
			Class.forName("com.mysql.jdbc.Driver");
		//2. Get links to databases
		// Create Connection Connections
		conn = DriverManager.getConnection(url,username,password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public static Connection getConnect(){
		return conn;
	}
}
DoddessDao.java

package com.imooc.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.imooc.db.JDBCTest;
import com.imooc.model.*;
import com.mysql.jdbc.PreparedStatement;
public class GoddessDao {
	public void addGoddess(Goddess g)throws Exception{
		Connection conn=JDBCTest.getConnect();
		String sql=""+"insert into imooc_goddess"+"(user_name,sex,age,birthday,email,mobile,create_user,create_date,"+
		"update_user,update_date,isdel)"+"values("+"?,?,?,?,?,?,?,current_date(),?,current_date(),?)";
		java.sql.PreparedStatement ptmt=conn.prepareStatement(sql);
		//precompile
		ptmt.setString(1, g.getUser_name());
		ptmt.setInt(2, g.getSex());
		ptmt.setInt(3, g.getAge());
		ptmt.setDate(4,new Date(g.getBirthday().getTime()));
		ptmt.setString(5, g.getEmail());
		ptmt.setString(6, g.getMobile());
		ptmt.setString(7, g.getCreate_user());
		ptmt.setString(8, g.getUpdate_user());
		ptmt.setInt(9, g.getIsdel());
		ptmt.execute();//implement
	}
	public void updateGoddess(Goddess g) throws SQLException{
		Connection conn=JDBCTest.getConnect();
		String sql=""+" update imooc_goddess set "+" user_name=?,sex=?,age=?,birthday=?,email=?,mobile=?, "+
		" update_user=?,update_date=current_date(),isdel=? "+" where id=? ";
		java.sql.PreparedStatement ptmt=conn.prepareStatement(sql);
		//precompile
		ptmt.setString(1, g.getUser_name());
		ptmt.setInt(2, g.getSex());
		ptmt.setInt(3, g.getAge());
		ptmt.setDate(4,new Date(g.getBirthday().getTime()));
		ptmt.setString(5, g.getEmail());
		ptmt.setString(6, g.getMobile());
		ptmt.setString(7, g.getUpdate_user());
		ptmt.setInt(8, g.getIsdel());
		ptmt.setInt(9, g.getId());
		ptmt.execute();//implement
	}
	public void delGoddess(Integer id) throws SQLException{
		Connection conn=JDBCTest.getConnect();
		String sql=""+" delete from imooc_goddess where id=?";
		java.sql.PreparedStatement ptmt=conn.prepareStatement(sql);
		//precompile
		
		ptmt.setInt(1, id);
		ptmt.execute();//implement
	}
	 public List<Goddess> query() throws SQLException{//Query multiple
		 Connection conn=JDBCTest.getConnect();
		 Statement stmt=conn.createStatement();
		 ResultSet rs=stmt.executeQuery("select user_name,age from imooc_goddess");
		
		 List<Goddess> gs=new ArrayList<Goddess>();
		 Goddess g=null;
		 while(rs.next())
		 {
			 g=new Goddess();
			 g.setUser_name(rs.getString("user_name"));
			 g.setAge(rs.getInt("age"));	
			 gs.add(g);
		 }
		 return gs;
	 }
	 //Query Individual
	 public Goddess get(Integer id) throws SQLException{
		 	Connection conn=JDBCTest.getConnect();
			String sql=""+" select * from imooc_goddess where id=?";
			java.sql.PreparedStatement ptmt=conn.prepareStatement(sql);
			
			//precompile
			ptmt.setInt(1, id);
			ResultSet rs=ptmt.executeQuery();//Query operation
			Goddess g=null;
			while(rs.next())
			{
				g=new Goddess();
				g.setId(rs.getInt("id"));
				g.setUser_name(rs.getString("user_name"));
				g.setAge(rs.getInt("age"));
				g.setSex(rs.getInt("sex"));
				g.setBirthday(rs.getDate("birthday"));
				g.setEmail(rs.getString("email"));
				g.setMobile(rs.getString("mobile"));
				g.setCreate_user(rs.getString("create_user"));
				g.setCreate_date(rs.getDate("create_date"));
				g.setUpdate_user(rs.getString("update_user"));
				g.setUpdate_date(rs.getDate("update_date"));
				g.setIsdel(rs.getInt("isdel"));
			}
			return g;
	 }
	 public Goddess get_byname(String name) throws SQLException{
		 Connection conn=JDBCTest.getConnect();
			String sql=""+" select * from imooc_goddess where user_name=?";
			java.sql.PreparedStatement ptmt=conn.prepareStatement(sql);
			
			//precompile
			ptmt.setString(1, name);
			ResultSet rs=ptmt.executeQuery();//Query operation
			Goddess g=null;
			while(rs.next())
			{
				g=new Goddess();
				g.setId(rs.getInt("id"));
				g.setUser_name(rs.getString("user_name"));
				g.setAge(rs.getInt("age"));
				g.setSex(rs.getInt("sex"));
				g.setBirthday(rs.getDate("birthday"));
				g.setEmail(rs.getString("email"));
				g.setMobile(rs.getString("mobile"));
				g.setCreate_user(rs.getString("create_user"));
				g.setCreate_date(rs.getDate("create_date"));
				g.setUpdate_user(rs.getString("update_user"));
				g.setUpdate_date(rs.getDate("update_date"));
				g.setIsdel(rs.getInt("isdel"));
			}
			return g;
	 }
	 
	 public List<Goddess> queryall(List<Map<String,Object>> params) throws SQLException{
		List<Goddess> result=new ArrayList<Goddess>();
		Connection conn=JDBCTest.getConnect();
		StringBuilder sb=new StringBuilder();
		sb.append(" select * from imooc_goddess where 1=1");
		if(params!=null&¶ms.size()>0){
			for(int i=0;i<params.size();i++){
				Map<String, Object> map=params.get(i);
				sb.append(" and "+ map.get("name")+" "+map.get("rela")+" "+map.get("value")); 
			}
		}
		java.sql.PreparedStatement ptmt=conn.prepareStatement(sb.toString());
		
		System.out.println(sb.toString());
		ResultSet rs=ptmt.executeQuery();
		
		Goddess g=null;
		while(rs.next()){
			g=new Goddess();
			g.setId(rs.getInt("id"));
			g.setUser_name(rs.getString("user_name"));
			g.setAge(rs.getInt("age"));
			g.setSex(rs.getInt("sex"));
			g.setBirthday(rs.getDate("birthday"));
			g.setEmail(rs.getString("email"));
			g.setMobile(rs.getString("mobile"));
			g.setCreate_date(rs.getDate("create_date"));
			g.setCreate_user(rs.getString("create_user"));
			g.setUpdate_date(rs.getDate("update_date"));
			g.setUpdate_user(rs.getString("update_user"));
			g.setIsdel(rs.getInt("isdel"));
			
			result.add(g);
		}
		return result;
		 
	 }
}


	goddessAction.java
package com.imooc.action;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.text.StyledEditorKit.ForegroundAction;

import com.imooc.dao.GoddessDao;
import com.imooc.model.Goddess;

public class goddessAction {

	public void add(Goddess g) throws Exception{//Adding functionality
		GoddessDao dao = new GoddessDao();
		dao.addGoddess(g);
		System.out.println("Added Successfully");
	}
	
	public void edit(Goddess g) throws SQLException{//Modification function
		GoddessDao dao = new GoddessDao();
		dao.updateGoddess(g);
		System.out.println("Successful revision");
	}
	
	public void del(Integer id) throws SQLException{//Delete function
		GoddessDao dao = new GoddessDao();
		dao.delGoddess(id);
		System.out.println("Successful deletion");
	}
	
	public List<Goddess> query() throws SQLException{//Full query function
		GoddessDao dao = new GoddessDao();
		return dao.query();
	}
	
	public List<Goddess> queryall(List<Map<String,Object>> params) throws SQLException
	{
		GoddessDao dao = new GoddessDao();
		return dao.queryall(params);
	}
	
	public Goddess get(Integer id) throws SQLException
	{
		GoddessDao dao = new GoddessDao();
		return dao.get(id);
	}
	
	public Goddess getbyname(String name) throws SQLException
	{
		GoddessDao dao = new GoddessDao();
		return dao.get_byname(name);
	}
}


Test.java
package com.imooc.test;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import com.imooc.action.goddessAction;
import com.imooc.model.Goddess;

public class Test {
	public static void show()
	{
		System.out.println("[1]Adding information");
		System.out.println("[2]Modify information");
		System.out.println("[3]adopt id Delete information");
		System.out.println("[4]Query information");
		System.out.println("[5]Display all information");
		System.out.println("[6]Exit System");
	}
	public static void show1(){
		System.out.println("[1]adopt id Query information");
		System.out.println("[2]Query information by name");
		System.out.println("[3]Exit this function");
	}
	public static void main(String[] args) throws Exception {
		/*goddessAction gac=new goddessAction();
		Goddess go=gac.get(3);
		System.out.println(go.toString());*/
		
		System.out.println("*********************************");
		System.out.println("*********Welcome to use this system***********");
		show();
		System.out.println("*********************************");
		int i,j;
		int m;
		String str;
		Scanner can= new Scanner(System.in);
		goddessAction gac=new goddessAction();
		while(true)
		{
			System.out.print("The choice you entered is:");
			i=can.nextInt();
			switch(i)
			{
				case 1:
					Goddess g1=new Goddess();
					System.out.print("Please enter your name:");
					str=can.next().toString();
					g1.setUser_name(str);
					System.out.print("Please enter age:");
					m=can.nextInt();
					g1.setAge(m);
					System.out.print("Please enter Gender [1] Female [2] Male [3] Genie:");
					m=can.nextInt();
					g1.setSex(m);
					System.out.print("Please enter your birthday,The format is: yyyy-MM-dd");
					str=can.next().toString();
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
					Date birthday=sdf.parse(str);
					g1.setBirthday(birthday);
					System.out.print("Please enter your email address:");
					str=can.next().toString();
					g1.setEmail(str);
					System.out.print("Please enter the telephone number:");
					str=can.next().toString();
					g1.setMobile(str);
					System.out.print("Enter the creator:");
					str=can.next().toString();
					g1.setCreate_user(str);
					System.out.print("Please enter the revised person:");
					str=can.next().toString();
					g1.setUpdate_user(str);
					System.out.print("Please enter whether your favorite 1 or 0:");
					m=can.nextInt();
					g1.setIsdel(m);
					gac.add(g1);
					continue;
				case 2:
					Goddess g2=new Goddess();
					System.out.print("Please enter your name:");
					str=can.next().toString();
					g2.setUser_name(str);
					System.out.print("Please enter Gender [1] Female [2] Male [3] Genie:");
					m=can.nextInt();
					g2.setSex(m);
					System.out.print("Please enter age:");
					m=can.nextInt();
					g2.setAge(m);
					System.out.print("Please enter your birthday,The format is: yyyy-MM-dd");
					str=can.next().toString();
					SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
					Date birthday1=sdf1.parse(str);
					g2.setBirthday(birthday1);
					System.out.print("Please enter your email address:");
					str=can.next().toString();
					g2.setEmail(str);
					System.out.print("Please enter the telephone number:");
					str=can.next().toString();
					g2.setMobile(str);
					System.out.print("Please enter the revised person:");
					str=can.next().toString();
					g2.setUpdate_user(str);
					System.out.print("Please enter whether your favorite 1 or 0:");
					m=can.nextInt();
					g2.setIsdel(m);
					System.out.print("Please enter what you want to modify. id: ");
					m=can.nextInt();
					g2.setId(m);
					gac.edit(g2);
					continue;
				case 3:
					System.out.print("Please enter the information you want to delete. id:");
					m=can.nextInt();
					gac.del(m);
					continue;
				case 4:
					while(true)
					{
						show1();
						int n;
						System.out.print("The choice you entered is:");
						n=can.nextInt();
						if(n==1)
						{
							System.out.print("Please enter the information you want to display. id:");
							m=can.nextInt();
							Goddess g3=gac.get(m);
							System.out.println(g3.toString());
						}
						else if(n==2)
						{
							System.out.print("Please enter the name of the information you want to display.:");
							str=can.next().toString();
							Goddess g3=gac.getbyname(str);
							System.out.println(g3.toString());
						}
						else if(n==3)
						{
							System.out.println("Sign out");
							break;
						}
						else {
							System.err.println("Without this option, please re-enter");
						}
					}
					continue;
				case 5:
				List<Goddess> gs = gac.query();
				for(Goddess godd: gs){
					System.out.println(godd.getId()+","+godd.getUser_name()+","+godd.getAge());
				}
				continue;
				case 6:
					System.out.println("Welcome to use next time!");
					System.exit(0);
			}
		}
	}
}






Keywords: Java SQL JDBC Database

Added by Mr.Fab on Mon, 15 Jul 2019 21:19:24 +0300