JDBC代码增删改查快速上手

文章展示了如何使用Java的JDBCAPI进行数据库的基本操作,包括插入、删除、更新和查询数据。提供了两种方法,一种是直接在主类中操作,另一种是将数据库操作封装到单独的类中。代码中包含了数据库连接、SQL语句的构建以及资源的释放。此外,还提及了一个Login类用于存储登录信息。
摘要由CSDN通过智能技术生成

数据库采用mysql8.0

软件为idea

每个模块均已封装展示,代码及注释如下:(可以直接使用,两种方法)

方法一:

package com.yx.jdbc.lse1;

import java.sql.*;

public class TextAll {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        //通常情况下main方法不会抛出异常 throws SQLException, ClassNotFoundException
        TextAll ta = new TextAll();
        //System.out.println(ta.st(ta.insert("as", 12345)));
        //System.out.println(ta.st(ta.delete("as")));
        System.out.println(ta.st(ta.update("asd","asdf",123456789)));
        ta.st3(ta.selectall());
        //System.out.println(ta.st2(ta.select("loginname")));
    }

    public String st(String sql) throws ClassNotFoundException, SQLException {
//用于对增加,删除,修改方法的调用
        Class.forName("com.mysql.cj.jdbc.Driver");//注册驱动
        String url = "jdbc:mysql://localhost:3306/hotel?characterEncoding=utf-8&useSSL=true&useTimezone=true";
        Connection connection = DriverManager.getConnection(url, "root", "root");//获取链接

        Statement statement = connection.createStatement();//获取执行对象
        int i = statement.executeUpdate(sql);//代码成功运行则i大于0 失败则false
        String a = i > 0 ? "over" : "false";
        if (statement != null && !statement.isClosed()) {//释放资源
            statement.close();
        }
        if (connection != null && !connection.isClosed()) {//释放资源
            connection.close();
        }

        return a;
    }

    public String insert(String loginname, int passowrd) {//添加方法
        String sql = "insert into e2(loginname,password) values(" + "'" + loginname + "'," + passowrd + ")";
        return sql;
    }

    public String delete(String loginname) {//删除方法
        String sql = "delete from e2 where loginname=" + "'" + loginname + "'";
        return sql;
    }

    public String update(String loginname1,String loginname, int passowrd) {//修改方法
        String sql = "update e2 set loginname=" + "'" + loginname + "'," + "password=" + passowrd + " where loginname=" +  "'" + loginname1 + "'";
        return sql;
    }

    public String st2(String sql) throws ClassNotFoundException, SQLException {
//用于查看单个数据方法调用
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/hotel?characterEncoding=utf-8&useSSL=true&useTimezone=true";
        Connection connection = DriverManager.getConnection(url, "root", "root");
        Statement statement = connection.createStatement();

        ResultSet rs = statement.executeQuery(sql);
        String a = null;
        while (rs.next()) {//判断是否为空
            String ln = rs.getString("loginname");
            int pw = rs.getInt("password");
            a = ln + "\t" + pw;
        }
        if (rs != null && !rs.isClosed()) {//释放资源
            rs.close();
        }
        if (statement != null && !statement.isClosed()) {//释放资源
            statement.close();
        }
        if (connection != null && !connection.isClosed()) {//释放资源 先判断是否可以释放 顺序固定
            connection.close();
        }
        return a;
    }

    public String select(String loginname) {//查看单个数据方法
        String sql = "select loginname, password from e2 where loginname =" + loginname;
        return sql;
    }

    public String selectall() {//查看所有数据方法
        String sql = "select loginname,password from e2";
        return sql;
    }

    public void st3(String sql) throws ClassNotFoundException, SQLException {
//用于查询所有数据方法的调用
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/hotel?characterEncoding=utf-8&useSSL=true&useTimezone=true";
        Connection connection = DriverManager.getConnection(url, "root", "root");
        Statement statement = connection.createStatement();

        ResultSet rs = statement.executeQuery(sql);
        String a = null;
        while (rs.next()) {
            String ln = rs.getString("loginname");
            int pw = rs.getInt("password");
            a = ln + "\t" + pw;
            System.out.println(a);//在循环里输出数据
        }
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        if (statement != null && !statement.isClosed()) {
            statement.close();
        }
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
    }
}

数据库截图如下

方法二:

        单独将数据库信息整理为一个类,用于暂时存储数据信息



public class Login {

	private String loginname;
	private int password;

	public Login(String loginname, int password) {
		super();
		this.loginname = loginname;
		this.password = password;
	}

	@Override
	public String toString() {
		return "Login [loginname=" + loginname + ", password=" + password + "]";
	}

	public Login() {

	}

	public String getLoginname() {
		return loginname;
	}

	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}

	public int getPassword() {
		return password;
	}

	public void setPassword(int password) {
		this.password = password;
	}

}

        将数据操作定义到另一个类中:

package text;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Jdbc {

	public Connection con;
	public PreparedStatement pst;
	public Statement st;
	public ResultSet rs;
	private static String driver = "com.mysql.cj.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/hotel";

	public Connection getConnection() {
		try {
			Class.forName(driver);
			con = DriverManager.getConnection(url, "root", "root");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}

	public void close(Statement st, Connection con) {
		try {
			if (st != null && !st.isClosed()) {
				st.close();
			}
			if (con != null && !con.isClosed()) {
				con.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean insert(String name, int passwor) {
		boolean b = false;
		try {
			con = getConnection();
			String sql = "insert into e2(loginname,passwor)values(?,?)";
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			pst.setInt(2, passwor);
			int i = pst.executeUpdate();
			b = i > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(pst, con);
		}
		return b;
	}

	public boolean delete(String name) {
		boolean b = false;
		try {
			con = getConnection();
			String sql = "delete from e2 where loginname=?";
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			int i = pst.executeUpdate();
			b = i > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(pst, con);
		}

		return b;
	}

	public boolean update(String name, int passwor, String name2) {
                //name是需要更改的数据,passwor和name2是更改后的数据
		boolean b = false;
		try {
			con = getConnection();
			String sql = "update e2 set loginname=?,passwor=? where loginname=?";
			pst = con.prepareStatement(sql);
			pst.setString(1, name2);
			pst.setInt(2, passwor);
			pst.setString(3, name);
			int i = pst.executeUpdate();
			b = i > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(pst, con);
		}
		return b;
	}

	public Login query(String name) {
		Login login = null;
		try {
			con = getConnection();
			String sql = "select loginname,passwor from e2 where loginname=?";
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			rs = pst.executeQuery();
			while (rs.next()) {
				String loginname = rs.getString("loginname");
				int password = rs.getInt("passwor");
				login = new Login(loginname, passwor);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(pst, con);
		}

		return login;
	}

	public List<Login> select() {
		List<Login> list =new ArrayList<Login>();
		try {
			con = getConnection();
			String sql = "select loginname,passwor from e2";
			st = con.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				String loginname = rs.getString("loginname");
				int password = rs.getInt("passwor");
				Login login = new Login(loginname, passwor);
				list.add(login);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(st, con);
		}
		return list;
	}
}

在下面代码之中hotel为数据库名称

String url = "jdbc:mysql://localhost:3306/hotel?characterEncoding=utf-8&useSSL=true&useTimezone=true";

如果想深入学习,个人推荐这个:
http://t.csdn.cn/vXoWZhttp://t.csdn.cn/vXoWZ

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值