mysql之jdbc

mysql之jdbcJDBCjava数据库连接用来操纵mysql数据库服务器的一套api接口。大部分是接口。javajdbc各种关系数据库mysqloraclesqlserverdb2jdbc操作m

大家好,又见面了,我是你们的朋友全栈君。

JDBC java数据库连接 用来操纵mysql数据库服务器的一套api接口。
大部分是接口。

java jdbc 各种关系数据库
mysql oracle sqlserver db2

jdbc操作mysql步骤
1)下载mysql jdbc驱动jar文件包。 mysql-xxxx.jar
mysql-connector-java-8.0.20.zip

2) 解压mysql-connector-java-8.0.20.zip 找到 mysql-connector-java-8.0.20.jar

3) 建立java项目,添加mysql-connector-java-8.0.20.jar依赖

4) 编写测试代码
package org.beiyou;

import java.sql.*;

public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String driver = “com.mysql.cj.jdbc.Driver”;
String url = “jdbc:mysql://localhost:33068/db?serverTimezone=PRC&useUnicode=true&characterEncoding=utf8”;
String username = “root”;
String password = “root”;

//加载驱动
Class.forName(“com.mysql.cj.jdbc.Driver”);

//建立数据库连接
Connection conn = DriverManager.getConnection(url,username,password);

PreparedStatement pst = conn.prepareStatement(“select id,name,address from stu”);
ResultSet rs = pst.executeQuery();
while(rs.next()){
String v = rs.getString(3);
System.out.println(v == null ? “地址未填写” : v);
}
conn.close();
}

public static void one(String[] args) throws SQLException {
Connection conn = DriverManager.getConnection(“jdbc:mysql:/db?user=root&serverTimezone=PRC”);
//System.out.println(conn);
//conn.createStatement().execute(“create table aa(a int)”);
//conn.createStatement().execute(“drop table if exists a1,a2,a3,a4,a5,a6,aa”);
//PreparedStatement ps = conn.prepareStatement(“show tables”);
PreparedStatement ps = conn.prepareStatement(“show full tables from `db` where table_type = ‘BASE TABLE'”);

ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1));
}
rs.close();
ps.close();
}
}

//加载驱动
Class.forName(“com.mysql.cj.jdbc.Driver”); mysql8 serveTimezone=PRC

Class.forname(“com.mysql.jdbc.Driver”); mysql5.6 5.5 5.1 user= password= useUnicode=true&characterEncoding=utf8

//建立数据库连接
Connection conn = DriverManager.getConnection(url,username,password);

 

java.sql.*;
DriverManager

 

1)Statement 语句对象

Connection conn = new DbUtil().getConn();
//Statement
try {
Statement s = conn.createStatement();
//s.execute() create drop grant revoke
//s.executeQuery() show select
//s.executeUpdate() insert delete update
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}

java jdbc mysql 插入数据时,返回自增id值
select max(id) from users ;
2)PreparedStatement

 

3).CallableStatement
delimiter $$
create procedure booknewadd(id int,in bn varchar(30),out s int,inout n int)
begin
insert into booknew values(id,bn);
select count(*) into s from booknew;
set n = n * n;
end$$
delimiter ;

CallableStatement cs = conn.prepareCall(“{call booknewadd(?,?,?,?)}”);
cs.setInt(1,2);
cs.setString(2,”《mysql数据库技术》”);
cs.registerOutParameter(3, Types.INTEGER);
cs.setInt(4,11);
cs.registerOutParameter(4, Types.INTEGER);
int i = cs.executeUpdate();
System.out.println(cs.getInt(3));
System.out.println(cs.getInt(4));
System.out.println(i);

编写DbUtil.java类, 工具类

DbUtil du = new DbUtil();
du.add(String sql,HashMap<String,Object>);
du.add(String sql,Object…objs);
du.execute(String sql,int id);

package com.fz.util;

import java.sql.*;
import java.util.*;

/**
* Created by webrx on 2017-08-16.
*/
public class DbUtil {
private String driver = “com.mysql.jdbc.Driver”; // 数据库驱动类
private String url = “jdbc:mysql://localhost:3306/oadb?useUnicode=true&characterEncoding=utf8&useSSL=true”;// url
private String uid = “root”; // 账号
private String pwd = “123”;// 密码
private int port = 3306;
private Connection conn = null;
private int currpage = 1;
private int pagesize = 5;
private int recordcount = 0;
private int pagecount = 0;
private String dbname = “oadb”;
private String host = “localhost”;

public void connect(String host, String user, String password, int port, String dbname) {
this.host = host;
this.url = url;
this.uid = user;
this.pwd = password;
this.dbname = dbname;
this.port = port;
this.url = String.format(“jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=utf8&useSSL=true”,this.host,this.port,this.dbname);
try {
Class.forName(driver);
this.conn = DriverManager.getConnection(url, uid, pwd);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public String getPk(String tablename) {
String pk = null;
DatabaseMetaData dbmd;
try {
dbmd = this.conn.getMetaData();
ResultSet rs = dbmd.getPrimaryKeys(this.dbname, null, tablename);
if (rs.next()) {
pk = rs.getString(4);
}
} catch (SQLException e) {
e.printStackTrace();
}
return pk;
}

public int add(String sql, Object[] values) {
int num = 0;
PreparedStatement pst;
try {
pst = this.conn.prepareStatement(sql);
int i = 0;
for (Object o : values) {
pst.setObject(++i, o);
}
num = pst.executeUpdate();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}

public int insert(String tablename, Map<String, Object> m) {
int num = 0;
StringBuilder n = new StringBuilder();
StringBuilder v = new StringBuilder();
for (String k : m.keySet()) {
v.append(“?,”);
n.append(k + “,”);
}
String sql = String.format(“insert into %s(%s) values(%s)”, tablename, n.toString().subSequence(0, n.length() – 1), v.toString().subSequence(0, v.length() – 1));
PreparedStatement pst;
try {
pst = this.conn.prepareStatement(sql);
int i = 0;
for (Object o : m.values()) {
pst.setObject(++i, o);
}
num = pst.executeUpdate();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}

public int deleteById(String tablename, Object id) {
int num = delete(tablename, this.getPk(tablename) + “=” + id);
return num;
}

public int delete(String tablename, String where) {
int num = 0;
String sql = String.format(“delete from %s where %s”, tablename, where);
try {
PreparedStatement pst = this.conn.prepareStatement(sql);
num = pst.executeUpdate();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}

public int delete(String tablename) {
int num = delete(tablename, “1=1”);
return num;
}

public Map<String, Object> queryById(String tablename, Object id) {
Map<String, Object> m = new HashMap<String, Object>();
String sql = String.format(“select * from %s where %s”, tablename, this.getPk(tablename) + “='” + id+”‘”);
try {
PreparedStatement pst = this.conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
int cc = rsmd.getColumnCount();
for (int i = 1; i <= cc; i++) {
String name = rsmd.getColumnLabel(i);
m.put(name, rs.getObject(name));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return m;
}

public int update(String tablename, Map<String, Object> m) {
int num = 0;
String pk = this.getPk(tablename);
if (m.containsKey(pk)) {
num = update(tablename, m, pk + “='” + m.get(pk)+”‘”);
} else {
num = update(tablename, m, “1=1”);
}
return num;
}

public int update(String tablename, Map<String, Object> m, String where) {
int num = 0;
StringBuilder s = new StringBuilder();
for (String k : m.keySet()) {
s.append(k + “=?,”);
}
String sql = String.format(“update %s set %s where %s”, tablename, s.toString().subSequence(0, s.length() – 1), where);
PreparedStatement pst;
try {
pst = this.conn.prepareStatement(sql);
int i = 0;
for (Object o : m.values()) {
pst.setObject(++i, o);
}
num = pst.executeUpdate();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}

public void close() {
if (this.conn != null) {
try {
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public int getCurrpage() {
return currpage;
}

public void setCurrpage(int currpage) {
this.currpage = currpage;
}

public int getPagesize() {
return pagesize;
}

public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}

public int getRecordcount() {
return recordcount;
}

public void setRecordcount(int recordcount) {
this.recordcount = recordcount;
}

public int getPagecount() {
return pagecount;
}

public void setPagecount(int pagecount) {
this.pagecount = pagecount;
}

/**
* host localhost
* user root
* pwd 123
* port 3306
*/
public DbUtil() {
try {
Properties pro = new Properties();
pro.load(DbUtil.class.getClassLoader().getResourceAsStream(“db.properties”));
this.driver = pro.getProperty(“db.driver”);
Class.forName(this.driver);
this.url = pro.getProperty(“db.url”);
this.uid = pro.getProperty(“db.user”);
this.pwd = pro.getProperty(“db.password”);
this.conn = DriverManager.getConnection(this.url, this.uid, this.pwd);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public DbUtil(String host,String user,String password,String dbname) {
this.host = host;
this.uid = user;
this.pwd = password;
this.url = String.format(“jdbc:mysql://%s:3306/%s?useUnicode=true&characterEncoding=utf8&useSSL=true”,this.host,this.dbname);
try {
Class.forName(driver);
this.conn = DriverManager.getConnection(url, uid, pwd);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public Connection getConn() {
return this.conn;
}

public int count(String tablename, String where) {
int num = 0;
String sql = String.format(“select count(*) from %s where %s”, tablename, where);
try {
PreparedStatement pst = this.conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
num = rs.getInt(1);
}
rs.close();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}

public List<Map<String, Object>> query(String tablename, String field) {
return query(tablename, field, “1=1”, “”);
}

public List<Map<String, Object>> query(String tablename) {
return query(tablename, “*”, “1=1”, “”);
}

public List<Map<String, Object>> query(String tablename, String field, String where, String order) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
String sql = String.format(“select %s from %s where %s %s”, field, tablename, where, order);
PreparedStatement pst;
try {
pst = this.conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
Map<String, Object> m = new HashMap<String, Object>();
int cc = rsmd.getColumnCount();
for (int i = 1; i <= cc; i++) {
String name = rsmd.getColumnLabel(i);
m.put(name, rs.getObject(name));
}
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}

public List<Map<String, Object>> page(int currpage, String tablename, String where, String order) {
return page(currpage, tablename, “*”, where, order);
}

public List<Map<String, Object>> page(int currpage, String tablename, String order) {
return page(currpage, tablename, “*”, “where 1=1”, order);
}

public List<Map<String, Object>> page(int currpage, String tablename) {
return page(currpage, tablename, “*”, “where 1=1”, “”);
}

public List<Map<String, Object>> page(int currpage, String tablename, String fields, String where, String order) {
this.currpage = currpage;
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
String sql = String.format(“select %s from %s %s %s limit ?,?”, fields, tablename, where, order);
String qqq = String.format(“select count(*) c from %s %s”, tablename, where);
try {
// 分页信息
PreparedStatement qpst = this.conn.prepareStatement(qqq);
ResultSet qrs = qpst.executeQuery();
if (qrs.next()) {
this.recordcount = qrs.getInt(“c”);
this.pagecount = this.recordcount % this.pagesize == 0 ? this.recordcount / this.pagesize : this.recordcount / this.pagesize + 1;
}
if (this.currpage < 1)
this.currpage = 1;
if (this.currpage > this.pagecount)
this.currpage = this.pagecount;

// 分页结果信息
PreparedStatement pst = this.conn.prepareStatement(sql);
pst.setInt(1, this.currpage * this.pagesize – this.pagesize);
pst.setInt(2, this.pagesize);
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
Map<String, Object> m = new HashMap<String, Object>();
int cc = rsmd.getColumnCount();
for (int i = 1; i <= cc; i++) {
String name = rsmd.getColumnLabel(i);
m.put(name, rs.getObject(name));
}
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}

public String pagebootstrap() {
StringBuilder s = new StringBuilder();
s.append(“<ul class=\”pagination\”>”);
int start = 1;
int end = 10;

if (this.currpage >= 7) {
start = this.currpage – 5;
end = this.currpage + 4;
}
if (this.currpage != 1) {
s.append(String.format(“<li><a class=\”prev\” href=\”?p=%d\”>上一页</a></li>”, this.currpage – 1));
}
for (int i = start; i <= end; i++) {
if (i > this.pagecount)
break;
if (this.currpage == i) {
s.append(String.format(“<li class=\”active\”><a href=\”javascript:void(0)\”>%d</a></li>”, i));
continue;
}
s.append(String.format(“<li><a href=\”?p=%d\”>%d</a></li>”, i, i));
}
if (this.currpage < this.pagecount) {
s.append(String.format(“<li><a class=\”next\” href=\”?p=%d\”>下一页</a></li>”, this.currpage + 1));
}
s.append(“</ul>”);
return s.toString();
}

public String pageinfo() {
StringBuilder s = new StringBuilder();
s.append(“<div class=\”page\”>”);
int start = 1;
int end = 10;

if (this.currpage >= 7) {
start = this.currpage – 5;
end = this.currpage + 4;
}
if (this.currpage != 1) {
s.append(String.format(“<a class=\”prev\” href=\”?p=%d\”>上一页</a>”, this.currpage – 1));
}
for (int i = start; i <= end; i++) {
if (i > this.pagecount)
break;
if (this.currpage == i) {
s.append(String.format(“<span>%d</span>”, i));
continue;
}
s.append(String.format(“<a href=\”?p=%d\”>%d</a>”, i, i));
}
if (this.currpage < this.pagecount) {
s.append(String.format(“<a class=\”next\” href=\”?p=%d\”>下一页</a>”, this.currpage + 1));
}
s.append(“</div>”);
return s.toString();
}

}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/154715.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • java验证工具_「verifycode」java工具类——验证码(VerifyCode) – seo实验室

    java验证工具_「verifycode」java工具类——验证码(VerifyCode) – seo实验室verifycodeimportjava.awt.BasicStroke;importjava.awt.Color;importjava.awt.Font;importjava.awt.Graphics2D;importjava.awt.image.BufferedImage;importjava.io.FileNotFoundException;importjava.io.IOEx…

  • thrift异步调用

    thrift异步调用关于异步,我找了很多资料,java方面的比较多,可c的少之又少,很多就是简单提一下,也么说怎么用,最后终于还是自己研究出来了异步分为服务端异步与客户端异步两部分,理论上他们两者是无关的,不论服务端同步与否,客服端都可以做成异步的。客户端异步客户端异步比较简单,服务端可以使用任何server,TThreadPoolServer或TNonblockingServer等随意,客户端不调用自动

  • 如何使用StarUML画类图[通俗易懂]

    此篇文档旨在介绍类图以及如何通过StarUML工具画类图。StarUML官网下载地址:http://staruml.io/download**什么是类图** 类图用于描述系统中所包含的类以及它们之间的相互关系,帮助简化对系统的理解。**类与接口的表现形式**矩形框:它代表一个类(Class)。类图分三层,第一层显示类的名称,如果是抽象类,则就用斜体显示。第二层是类的特性,通常就是字段和属性…

  • dpkg配置包出错_dpkg-reconfigure

    dpkg配置包出错_dpkg-reconfigure2021-10-18by崔斐然dpkg:处理软件包xxx(–configure)时出错解决方法来源:https://blog.csdn.net/jf_xu/article/details/82285008dpkg:处理软件包libicu-dev(–configure)时出错:依赖关系问题-仍未被配置dpkg:依赖关系问题使得libxml2-dev:amd64的配置工作不能继续:libxml2-d…

  • MAC 系统安装 Maven 及环境变量配置

    MAC 系统安装 Maven 及环境变量配置1、概述本文主要为在MAC苹果系统下安装Maven及环境变量配置Maven是Apache下的一个纯Java开发的开源项目。基于项目对象模型(缩写:POM)概念,Maven利用一个中央信息片断能管理一个项目的构建、报告和文档等步骤。Maven是一个项目管理工具,可以对Java项目进行构建、依赖管理。Maven也可被用于构建和管理各种项目,例如C#,Ruby,Scala和其他语言编写的项目。Maven曾是Jakarta项目的子项目,现为由Apache软件基金会主持

  • javascript实现一个自制网页音乐播放器

    javascript实现一个自制网页音乐播放器序接触简书也有一段日子了,这中间的时光还是比较轻松加愉快的,那种可以和他人分享知识的欣喜和愉悦的确是非常棒。我一向都是觉得专心写自己的文就可以了,不会总是纠结有多少人在看,有多少点击等等。用心写好自己的文,体会那种分享的快乐,就可以了。之前写的《js常用方法和一些封装》系列暂且告一段落,接下来,我会通过各种案例,来分享javascript的各种技巧,所以最终将这个系列的名称定为:《从案例中学习

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号