JDBC之Java连接mysql实现增删改查

使用软件:mysql、eclipse

链接步骤:

1.注册驱动

2.创建一个连接对象

3.写sql语句

4.执行sql语句并返回一个结果或者结果集

5.关闭链接(一般就是connection、statement、setresult)这三个连接对象,关闭顺序一般是(setresult    --->  statement  -->  setresult  )

一、直接连接方法:(这种方法就是讲sql语句和结果所有的步骤写在一起) 不建议使用该方法

 1 public static void main(String[] args) {
 2         String url = "jdbc:mysql://localhost:3306/students";
 3         String user = "root";
 4         String password = "admin";
 5         Connection conn = null;
 6         Statement st = null;
 7
 8         try {
 9             // 1. 注册驱动
10             Class.forName("com.mysql.jdbc.Driver");
11             // 2. 创建一个链接对象
12             conn = DriverManager.getConnection(url,user,password);
13             // 3. 创建一个sql语句的发送命令对象
14             String sql = "insert into student values(‘2001‘,‘Tom‘,‘20‘,‘7000‘)";
15             st= conn.createStatement();
16             // 4. 执行sql语句,拿到查询的结果集对象
17             st.executeQuery(sql);20         } catch (Exception e) {
21             e.printStackTrace();
22         }finally {
23             // 5. 关闭链接 ,命令对象 ,结果集
24             if(st != null) {
25                 try {
26                     st.close();
27                 } catch (Exception e) {
28                     e.printStackTrace();
29                 }
30             }
31             if(conn != null) {
32                 try {
33                     conn.close();
34                 } catch (Exception e) {
35                     e.printStackTrace();
36                 }
37             }
38         }

二、建立工具类方法,将必要的几步写一个类,使用的时候直接调用建议使用

1.注册驱动、创建连接对象、关闭资源    这三部一般可以写一个类,由于写sql语句和执行sql语句的结果不一致,所以可以将其在用到的时候在写

2.一般写工具类都是写成静态方法,以方便调用

//这是工具类:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JdbcUtils {
	private static String driverName = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/student_achievement_system";
	private static String user = "root";
	private static String password = "admin";
	/**
	 * 链接数据库
	 */
	static {
		try {
			Class.forName(JdbcUtils.driverName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取链接对象connection
	 * @return
	 */
	public static Connection getConnection() {
		try {
			return DriverManager.getConnection(JdbcUtils.url, JdbcUtils.user, JdbcUtils.password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 关闭资源
	 * @param conn
	 * @param st
	 * @param rs
	 */
	public static void close(Connection conn,Statement st,ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(st != null) {
			try {
				st.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

  

//这是对数据库的基本操作类

// 增加、删除、更新、查找一条、查找所有的方法

public class StudentsDaoImpl implements IStudentsDao {
    //增加
	@Override
	public int save(Students student) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "insert into students values(?,?,?,?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, student.getStudentId());
			ps.setString(2, student.getStudentName());
			ps.setString(3, student.getSex());
			ps.setString(4, student.getPhoneNo());
			ps.setString(5, student.getAddress());
			ps.setDate(6, (Date) student.getBirthday());
			int row = ps.executeUpdate();
			return row;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtils.close(conn, ps, null);
		}
		return 0;
	}
      //删除
	@Override
	public int delete(int studentId) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "delete from students where studentId=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, studentId);
			int row = ps.executeUpdate();
			return row;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtils.close(conn, ps, null);
		}
		return 0;
	}
    //更新
	@Override
	public int update(int studentId, Students student) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "update students set studentName=?,sex=?,phoneNo=?,address=?,birthday=? where studentId=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, student.getStudentName());
			ps.setString(2, student.getSex());
			ps.setString(3, student.getPhoneNo());
			ps.setString(4, student.getAddress());
			ps.setDate(5, ((Date) student.getBirthday()));
			ps.setInt(6, studentId);
			int row = ps.executeUpdate();
			return row;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtils.close(conn, ps, null);
		}
		return 0;
	}
      //查找一条数据
	@Override
	public Students getByStudentId(int studentId) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "select * from students where studentId=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, studentId);
			rs = ps.executeQuery();
			if(rs.next()) {
				Students student = new Students();
				student.setStudentId(rs.getInt("studentId"));
				student.setStudentName(rs.getString("studentName"));
				student.setSex(rs.getString("sex"));
				student.setPhoneNo(rs.getString("phoneNo"));
				student.setAddress(rs.getString("address"));
				student.setBirthday(rs.getDate("birthday"));
				return student;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtils.close(conn, ps, rs);
		}
		return null;
	}
      //查找所有数据
	@Override
	public List<Students> getAll() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "select * from students";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			List<Students> studentsList = new ArrayList<>();
			while(rs.next()) {
				Students student = new Students();
				student.setStudentId(rs.getInt("studentId"));
				student.setStudentName(rs.getString("studentName"));
				student.setSex(rs.getString("sex"));
				student.setPhoneNo(rs.getString("phoneNo"));
				student.setAddress(rs.getString("address"));
				student.setBirthday(rs.getDate("birthday"));
				studentsList.add(student);
			}
			return studentsList;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtils.close(conn, ps, rs);
		}
		return null;
	}}

  

原文地址:https://www.cnblogs.com/gaobingbing/p/10314248.html

时间: 2024-08-24 19:46:00

JDBC之Java连接mysql实现增删改查的相关文章

Java连接MySQL数据库增删改查通用方法

Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类下面写好多方法,要是多个数据库,就要写多个类多个方法,导致代码编写太过于繁琐,所以为了改变这样的繁琐,我将连接数据库的方法进行了一系列的封装,使用户传入一个对象值Object就可以得到想要的. 我在之前写过一篇普通的Java连接MySQL数据库,大家可以看看,以便对比参考之后就知道差距了  数据库--MySQL-->Java篇 接下来我给大家讲讲如何将

java连接mysql以及增删改查操作

java连接数据库的代码基本是固定的,步骤过程觉得繁琐些,代码记起来对我来说是闹挺.直接上代码: (温馨提醒:你的项目提前导入连接数据库的jar包才有的以下操作 ) 1 class DBConnection{ 2 3 // 驱动类名 4 String driver="com.mysql.jdbc.Driver"; 5 // URL格式,最后为数据库名 6 String url="jdbc:mysql://localhost:3306/javaTest?useUnicode=t

java连接mysql数据库增删改查操作记录

1. 连接数据库,得到数据库连接变量 注意连接数据库的时候 (1)打开DB Browser 新建一个Database Driver,注意添加Driver JARs的时候添加的包,我的是mysql-connector-java-5.0.3-bin.jar (2)要将数据库jar包拷贝到工程下的WEB-INF\lib下 import java.sql.Connection;//java包 public class DBConnection { private String dbDriver="com

MySQL---数据库从入门走上大神系列(二)-用Java对MySQL进行增删改查

上节已经学会对MySQL进行简单的增删改查了,那么,我们如何实现用Java来对数据库操作增删改呢. 本节将用Java演示对MySQL进行增删改查. 简单的来说,分为4个步骤: 1.加载连接器(驱动)   通过Driver类 (最好用类反射来加载,更加灵活) 2.建立与数据库的连接 3.获取语句对象 4.对数据库进行操作(增删改查) 其实第一步现在可以不用写了,高版本的MySQL已经在内部帮我们写好了第一步,但是,为了兼容性更好(兼容低版本的MySQL)我们最好还是写上第一步. 我们先看一下原数据

Java连接MongoDB进行增删改查

1.导入必须的包: 详情看项目:http://pan.baidu.com/s/1cvDAOY 2.通过Myeclipse创建WEB项目 3. 3.bean:创建实体类 package com.bean; import java.io.Serializable; import java.util.Date; /** * @since 对应于mongodb中的数据库test中的表com * @author think * */ public class Company implements Seri

java连接MySQL进行增删改操作时报错

java连接MySQL数据库后执行execute语句,控制台总是报错,如下: Exception in thread "main" java.sql.SQLException: Could not retrieve transation read-only status server ……? Caused by: java.sql.SQLException: Unknown system variable 'tx_read_only' 我捣鼓了一整个下午,参考别人的代码,甚至完全套用别

jsp-2 简单的servlet连接mysql数据库 增删改查

连接mysql数据库的操作 有增删改查 用的包有 commons-lang3-3.5 mysql-connector-java-5.1.40-bin 但是实际上也就是 数据查询和数据处理两种 所以对数据库的操作DAO只有两种方法 package com.javaweb.dao; import java.lang.reflect.Field;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.Re

java对mysql的增删改查

-----连接数据库 package connectdb;import java.sql.*;class Dbcon { // 此处连接数据库,独立开一个类,以后操作数据库的每次连接就不用写这么多 public Connection getCon() { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); // 其中test是我们要链接的数据库,user是数据库用户名,password是数据库密码.

java 连接oracle 进行增删改查

1.在DAO层新增类OraclePersionDao package com.test.dao; import java.sql.*; /** * Created by wdw on 2017/9/16. */ public class OraclePersionDao { // 数据库驱动类 private String dbDriver = "oracle.jdbc.driver.OracleDriver"; // 连接数据库url private String dbURL = &