案例Java+sql基本操作
java sql in 用法

在Java中,SQL的"IN"语句用于在WHERE子句中指定一个值列表,并检查某个列中的值是否在这个列表中。
以下是一个基本的Java使用SQL IN语句的例子:```javaimport java.sql.*;public class Main {public static void main(String[] args) {String url = "jdbc:mysql://localhost:3306/mydatabase";String username = "username";String password = "password";try {Connection conn = DriverManager.getConnection(url, username, password);String sql = "SELECT * FROM mytable WHERE column_name IN (?, ?, ?)";PreparedStatement stmt = conn.prepareStatement(sql);stmt.setInt(1, 10);stmt.setInt(2, 20);stmt.setInt(3, 30);ResultSet rs = stmt.executeQuery();while(rs.next()) {System.out.println(rs.getString("column_name"));}rs.close();stmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}}}```在这个例子中,我们连接到名为"mydatabase"的数据库,使用用户名"username"和密码"password"。
Java实现简单的SQL动态组装工具类

Java实现简单的SQL动态组装⼯具类第⼀版package com.zh.oukele.util;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class CreateSqlUtil {public static void main(String[] args) {Map<String ,Object> map = new HashMap<>();map.put("stuName","欧可乐");map.put("stuAge",20);map.put("stuSex","男");map.put("Key_stuId","ASDF");map.put("Key_stuSex","ASDF");try {System.out.println(getSql("table_name", "delete", map, false, ""));} catch (Exception e) {e.printStackTrace();}}/*** 动态组装简单sql语法* @param tableName 表名* @param operation 操作标识符 select|delete|update ,默认为 select* @param mapData 数据的map集合* @param useMySQL true|false , false 为使⽤动态组装SQL,true为使⽤⾃已的sql* @param mySql ⾃已的sql* 注意:update 这⾥,where xxx = xxx ,的时候,mapData ⾥的键必须要有 Key_ 前缀(其他的并不影响到)** @return* @throws Exception*/public static String getSql(String tableName, String operation, Map<?,?> mapData,boolean useMySQL,String mySql) throws Exception { String sql = null;// 使⽤组装sql的功能if( !useMySQL){if( !(tableName != null && !tableName.equals("") && tableName.length() > 0 ) ){throw new Exception(" 参数 tableName 的值为空!");}else if( !(mapData != null && !mapData.equals("") && mapData.size() > 0 ) ){throw new Exception(" 参数 mapData 的值为空!");}// 操作标识默认为 selectString operations = "select";String condition = " a.* from " + tableName + " a where ";if( operation != null && !operation.equals("") ){if( operation.equals("update") || operation.equals("UPDATE") ){operations = "update";condition = " " + tableName + " a set ";}else if( operation.equals("delete") || operation.equals("DELETE") ){operations = "delete";condition = " from " + tableName + " a where ";}else if( operation.equals("insert") || operation.equals("INSERT") ){operations = "insert";condition = " into " + tableName + " values (";String link = "";Iterator<?> iterator = mapData.keySet().iterator();while (iterator.hasNext()) {String next = (String) iterator.next();condition += link + next;link = ",";}condition += ") values( ";}}String value= "";String link ="";String keyValueOperations = " where ";Iterator<? extends Map.Entry<?, ?>> iterator = mapData.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<?, ?> next = iterator.next();if( next.getValue() instanceof String ){value = "'" + next.getValue() +"'";}else {value = "" + next.getValue() +"";}if( next.getKey().toString().lastIndexOf("Key_") == -1 ){if( !operations.equals("insert")){if( operations.equals("select") || operations.equals("delete")){condition += link + "a." + next.getKey();condition += "=" + value;link = " and ";}else {condition += link + "a." + next.getKey();condition += "=" + value;link = ",";}}else {condition += link + value;link = ",";}}else {continue;}}// 组装 insert sql 的结尾if( operations.equals("insert") ){condition += ")";}else if(operations.equals("update")){ // 组装 update sql 的结尾condition += " where ";String and = "";Iterator<? extends Map.Entry<?, ?>> iterator1 = mapData.entrySet().iterator();while (iterator1.hasNext()) {Map.Entry<?, ?> next = iterator1.next();if( next.getValue() instanceof String ){value = "'" + next.getValue() +"'";}else {value = "" + next.getValue() +"";}String key = next.getKey().toString();if( stIndexOf("Key_") != -1 ){key = key.substring(key.indexOf("Key_")+ 4,key.length());condition += and +"a." +key + "=" + value;and = " and ";}}}sql = operations + condition;}else { // 不使⽤组装sql的功能sql = mySql;}return sql;}}使⽤案例:public static void main(String[] args) throws Exception {Map<String ,Object> map = new HashMap<>();map.put("stuName","欧可乐");map.put("stuAge",20);map.put("stuSex","");map.put("Key_stuId","XXX");map.put("Key_stuSex","VVV");String select = getSql1("table_name", "select", map, false, "");System.out.println(select);System.out.println();String insert = getSql1("table_name", "insert", map, false, "");System.out.println(insert);System.out.println();String delete = getSql1("table_name", "delete", map, false, "");System.out.println(delete);System.out.println();String update = getSql1("table_name", "update", map, false, "");System.out.println(update);}⽣成的SQL语句:第⼆版修改版本⼀组装insert语法时的⼀些bug,新增组装查询SQL时, 可使⽤ a.xxx is not null 条件查询/*** 动态组装简单sql语法* @param tableName 表名* @param operation 操作标识符 select|delete|update ,默认为 select* @param mapData 数据的map集合* @param useMySQL true|false , false 为使⽤动态组装SQL,true为使⽤⾃已的sql* @param mySql ⾃已的sql* 注意:update 这⾥,where xxx = xxx ,的时候,mapData ⾥的键必须要有 Key_ 前缀(其他的并不影响到)** @return* @throws Exception*/public static String getSql2(String tableName, String operation, Map<?,?> mapData,boolean useMySQL,String mySql) throws Exception { String sql = null;// 使⽤组装sql的功能if( !useMySQL){if( !(tableName != null && !tableName.equals("") && tableName.length() > 0 ) ){throw new Exception(" 参数 tableName 的值为空!");}else if( !(mapData != null && !mapData.equals("") && mapData.size() > 0 ) ){throw new Exception(" 参数 mapData 的值为空!");}// 键组装// 操作标识默认为 selectString operations = "select";String condition = " a.* from " + tableName + " a where ";if( operation != null && !operation.equals("") ){if( operation.equals("update") || operation.equals("UPDATE") ){operations = "update";condition = " " + tableName + " a set ";}else if( operation.equals("delete") || operation.equals("DELETE") ){operations = "delete";condition = " from " + tableName + " a where ";}else if( operation.equals("insert") || operation.equals("INSERT") ){operations = "insert";condition = " into " + tableName + " values (";String link = "";Iterator<?> iterator = mapData.keySet().iterator();while (iterator.hasNext()) {String next = (String) iterator.next();if( stIndexOf("Key_") == -1){condition += link + next;link = ",";}}condition += ") values( ";}}// 值组装String value= "";String link ="";String keyValueOperations = " where ";Iterator<? extends Map.Entry<?, ?>> iterator = mapData.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<?, ?> next = iterator.next();if( next.getValue() instanceof String ){value = "'" + next.getValue() +"'";}else {if( next.getValue() == null ){value = "";}else {value = "" + next.getValue() +"";}}if( next.getKey().toString().lastIndexOf("Key_") == -1 ){if( !operations.equals("insert")){if( operations.equals("select") || operations.equals("delete")){condition += link + "a." + next.getKey();if( value.equals("") ){condition += value;}else {condition += "=" + value;}link = " and ";}else {condition += link + " a." + next.getKey();condition += "=" + value;link = ",";}}else {condition += link + value;link = ",";}}else {continue;}}// 组装 insert sql 的结尾if( operations.equals("insert") ){condition += ")";}else if(operations.equals("update")){ // 组装 update sql 的结尾condition += " where ";String and = "";Iterator<? extends Map.Entry<?, ?>> iterator1 = mapData.entrySet().iterator();while (iterator1.hasNext()) {Map.Entry<?, ?> next = iterator1.next();if( next.getValue() instanceof String ){value = "'" + next.getValue() +"'";}else {value = "" + next.getValue() +"";}String key = next.getKey().toString();if( stIndexOf("Key_") != -1 ){key = key.substring(key.indexOf("Key_")+ 4,key.length());condition += and +"a." +key + "=" + value;and = " and ";}}}sql = operations + condition;}else { // 不使⽤组装sql的功能sql = mySql;}return sql;}View Code使⽤案例:public static void main(String[] args) throws Exception {Map<String ,Object> map = new HashMap<>();map.put("stuName","欧可乐");map.put("stuAge",20);map.put("stuSex","");map.put("Key_stuId","XXX");map.put("Key_stuSex","VVV");String select = getSql2("table_name", "select", map, false, "");System.out.println(select);System.out.println();String insert = getSql2("table_name", "insert", map, false, "");System.out.println(insert);System.out.println();String delete = getSql2("table_name", "delete", map, false, "");System.out.println(delete);System.out.println();String update = getSql2("table_name", "update", map, false, "");System.out.println(update);}⽣成的SQL语句:简单动态组装select语法案例:public static void main(String[] args) throws Exception {Map<String ,Object> map = new HashMap<>();map.put("stuName","欧可乐");map.put("stuSex","男");map.put("stuSex is not null or a.stuAge > 19 ",null);String select = getSql2("table_name", "select", map, false, ""); System.out.println(select);}⽣成的SQL语句:。
java根据传入sql语句进行数据库查询的方法

java根据传入sql语句进行数据库查询的方法在现代软件开发领域,Java已经成为了一种非常流行和广泛使用的编程语言之一。
尤其是在与数据库的交互方面,Java提供了丰富的API和工具,使得开发人员可以轻松地进行数据库操作。
在本篇文章中,我将探讨一种重要的Java编程技巧,即使用传入的SQL语句进行数据库查询的方法。
1. 什么是传入SQL语句进行数据库查询的方法?传入SQL语句进行数据库查询,是指在Java代码中,我们可以动态地构建和执行SQL查询语句。
相比于静态地写死SQL语句,这种方法更加灵活和可扩展,能够适应不同的查询需求。
2. Java中如何实现传入SQL语句进行数据库查询?Java提供了多种方式来实现传入SQL语句进行数据库查询的方法。
下面,我将介绍其中两种较常见的方式。
2.1 PreparedStatementPreparedStatement是一种预编译的SQL语句对象,允许我们在执行SQL查询之前传入参数。
通过使用占位符,我们可以动态地向SQL语句中插入参数,从而实现传入SQL语句进行数据库查询的功能。
例如:```String sql = "SELECT * FROM users WHERE id = ?";PreparedStatement pstmt =connection.prepareStatement(sql);pstmt.setInt(1, id);ResultSet rs = pstmt.executeQuery();```在上述代码中,我们首先定义了一个SQL语句,其中包含了一个占位符"?"。
我们通过调用setInt()方法,将id值传入占位符中。
通过执行executeQuery()方法,我们可以获得查询结果集。
2.2 SQLBuilderSQLBuilder是一种基于构建器模式的工具,可以帮助我们更加便捷地构建复杂的SQL查询语句。
sql菜鸟教程

sql菜鸟教程SQL 是一种用于管理关系型数据库的编程语言。
它可以用来创建、修改和查询数据库中的表格和数据。
SQL 学习的第一步是了解如何创建数据库。
可以使用`CREATE DATABASE` 命令来创建一个新的数据库。
例如,下面的代码会创建一个名为 `mydatabase` 的数据库:```sqlCREATE DATABASE mydatabase;```接下来,需要创建一个表格来存储数据。
可以使用 `CREATE TABLE` 命令来创建一个新的表格。
例如,下面的代码会创建一个名为 `customers` 的表格,其中包含了 `id`、`name` 和`email` 列:```sqlCREATE TABLE customers (id INT PRIMARY KEY,name VARCHAR(255),email VARCHAR(255));```添加数据到表格中,可以使用 `INSERT INTO` 命令。
例如,下面的代码会向 `customers` 表格中插入一条新的记录:```sqlINSERT INTO customers (id, name, email)VALUES(1,'JohnDoe','*******************');```查询数据可以使用 `SELECT` 命令。
例如,下面的代码会查询`customers` 表格中的所有记录:```sqlSELECT * FROM customers;```如果只想查询特定的列,可以在 `SELECT` 命令中指定列的名称。
例如,下面的代码只会返回 `name` 列的值:```sqlSELECT name FROM customers;```更新现有的记录时,可以使用 `UPDATE` 命令。
例如,下面的代码会将 `id` 为 1 的记录的 `name` 列更新为 `'Jane Doe'`:```sqlUPDATE customersSET name = 'Jane Doe'WHERE id = 1;```删除记录时,可以使用 `DELETE` 命令。
java sql 正则

java sql 正则Java SQL 正则在Java编程中,我们经常需要与数据库进行交互,而SQL是一种用于操作和管理关系型数据库的标准语言。
在处理数据库查询时,我们常常需要使用正则表达式来处理和过滤数据。
正则表达式是一种强大的文本匹配工具,它可以用于在字符串中匹配和查找特定的模式。
在Java中,我们可以使用java.util.regex包提供的类来处理正则表达式。
在SQL查询中,正则表达式可以用于匹配和过滤数据,提高查询效率和准确性。
1. 在Java中使用正则表达式处理SQL查询在Java中,我们可以使用Pattern和Matcher类来处理正则表达式。
Pattern类表示一个正则表达式的编译表示,而Matcher类是一个匹配器,用于对输入字符串进行匹配操作。
我们需要编写一个正则表达式,以定义我们要匹配的模式。
例如,我们可以使用正则表达式"SELECT\s+\*\s+FROM\s+users"来匹配一个简单的SELECT语句,其中\s表示空白字符,+表示匹配一个或多个前面的元素。
然后,我们需要使用Pattern类的compile()方法将正则表达式编译为一个Pattern对象。
接下来,我们可以使用Matcher类的find()方法来查找输入字符串中与正则表达式匹配的部分。
2. 在SQL查询中使用正则表达式在SQL查询中,我们可以使用正则表达式来过滤和匹配数据。
例如,我们可以使用正则表达式来匹配符合特定模式的字符串,或者使用正则表达式来替换字符串中的特定内容。
在Java中,我们可以使用SQL的LIKE操作符来实现对字符串的模糊匹配。
例如,我们可以使用以下查询来获取所有以"J"开头的用户名:SELECT * FROM users WHERE username LIKE 'J%'然而,LIKE操作符只能进行简单的模糊匹配,而不能实现复杂的模式匹配。
java.sql 详解

Java.sql详解Java.sql是Java语言中用于处理数据库操作的API,它提供了用于连接数据库、执行SQL查询和更新、处理结果集等功能。
通过使用Java.sql,开发人员可以轻松地与关系型数据库进行交互,从而在Java应用程序中实现数据持久化。
以下是Java.sql的一些主要功能和组件:1.数据库连接要使用Java.sql进行数据库操作,首先需要建立与数据库的连接。
Java.sql提供了java.sql.DriverManager类和java.sql.Connection接口来管理数据库连接。
通过调用DriverManager的getConnection()方法并传递适当的连接字符串和凭据,可以建立与数据库的连接。
1.SQL语句执行一旦建立了数据库连接,就可以使用java.sql.Statement、java.sql.PreparedStatement和java.sql.CallableStatement等接口来执行SQL语句。
Statement用于执行静态SQL语句,而PreparedStatement用于执行参数化SQL语句。
这两种方式都可以执行查询和更新操作。
CallableStatement用于执行存储过程。
1.结果集处理执行SQL查询后,将返回一个java.sql.ResultSet对象,该对象表示查询结果集。
ResultSet提供了用于检索数据的方法,如next()、getInt()、getString()等。
通过遍历结果集,可以获取查询结果并进行处理。
1.事务管理Java.sql还提供了事务管理功能,以确保数据的完整性和一致性。
通过使用java.sql.Connection的setAutoCommit()和commit()方法,可以控制事务的提交和回滚。
在执行一系列数据库操作后,可以使用commit()方法将它们提交到数据库,或者使用rollback()方法撤销它们。
1.异常处理Java.sql还提供了异常处理机制,以处理在数据库操作中可能出现的错误和异常情况。
Java实现对Sql语句解析

Java实现对Sql语句解析最近要实现⼀个简易的数据库系统,除了要考虑如何⾼效的存储和访问数据,建⽴表关系外,对基本的sql查询语句要做⼀个解析,这样我们才能知道⽤户的查询要求;因为时间关系,参考了已有的⼀篇⽂章,并对其实现中出的⼩问题给予更正,在这⾥跟⼤家共享⼀下。
原⽂请查阅第⼀步:先对sql语句进⾏预处理;对于⽤户,我们应该接受各种形式的查询语句书写,单⾏或者多⾏,语句中单个空格或者多个空格的间隔等等。
但是我们要解析sql语句,就⾸先要让对它们做标准化,这样才能进⾏我们下⼀步处理。
系统中的处理要求:1)消除SQL语句前后的空⽩,将其中的连续空⽩字符(包括空格,TAB和回车换⾏)替换成单个空格;2)将sql语句全变成⼩写形式(或⼤写形式);3)在SQL语句的尾后加上结束符号“ENDOFSQL”(原因后⾯解释)例如:⽤户输⼊:“select c1,c2,c3 from t1,t2, t3 where condi1=5 and condi6=6 or condi7=7 order by g1,g2”通过预处理应该为:“select c1,c2,c3 from t1,t2,t3 where condi1=5 and condi6=6 or condi7=7 order by g1,g2”第⼆步:将查询语句切分为语句块;以查询语句为例(本⽂中主要是以查询语句作为例⼦讲解,其它删除,插⼊等语句原理于此类似,因为查询语句相对复杂,所以⽤来i讲解),正如上⾯我们标准化后的语句⼀样,我们要进⾏下⼀步的,对表中数据的处理,⾸先要知道是对那些表处理,要满⾜那些条件,输出那些属性,以什么顺序输出等。
所以查询语句就可以分割为以下⼏个块:1)select c1,c2,c3 from:属性输出块;块头(start)select,块尾(end)from,这个块我们关⼼的信息(body):c1,c2,c3;以下块类似分析2)from....where; 涉及数据表块。
java格式化sql

java格式化sql在⽇志分析中,经常会对记录的sql进⾏分析,所以将⼀整⾏sql格式化,进⾏多⾏缩就显得很有必要,许多数据库客户端都提供sql的格式化功能,但复杂的多层嵌套sql往往格式化的l还不够友好,所以就⾃⼰造了个。
import java.util.HashSet;import java.util.LinkedList;import java.util.Set;import java.util.StringTokenizer;public class BasicFormatterImpl {private static final Set<String> BEGIN_CLAUSES = new HashSet<String>();private static final Set<String> END_CLAUSES = new HashSet<String>();private static final Set<String> LOGICAL = new HashSet<String>();private static final Set<String> QUANTIFIERS = new HashSet<String>();private static final Set<String> DML = new HashSet<String>();private static final Set<String> MISC = new HashSet<String>();static final String indentString = " ";static final String initial = "\n ";public String format(String source) {return new FormatProcess(source).perform().trim();}static {BEGIN_CLAUSES.add("left");BEGIN_CLAUSES.add("right");BEGIN_CLAUSES.add("inner");BEGIN_CLAUSES.add("outer");BEGIN_CLAUSES.add("group");BEGIN_CLAUSES.add("order");END_CLAUSES.add("where");END_CLAUSES.add("set");END_CLAUSES.add("having");END_CLAUSES.add("join");END_CLAUSES.add("from");END_CLAUSES.add("by");END_CLAUSES.add("join");END_CLAUSES.add("into");END_CLAUSES.add("union");LOGICAL.add("and");LOGICAL.add("or");LOGICAL.add("when");LOGICAL.add("else");LOGICAL.add("end");QUANTIFIERS.add("in");QUANTIFIERS.add("all");QUANTIFIERS.add("exists");QUANTIFIERS.add("some");QUANTIFIERS.add("any");DML.add("insert");DML.add("update");DML.add("delete");MISC.add("select");MISC.add("on");}private static class FormatProcess {boolean beginLine = true;boolean afterBeginBeforeEnd = false;boolean afterByOrSetOrFromOrSelect = false;boolean afterValues = false;boolean afterOn = false;boolean afterBetween = false;boolean afterInsert = false;int inFunction = 0;int parensSinceSelect = 0;private LinkedList<Integer> parenCounts = new LinkedList<Integer>();private LinkedList<Boolean> afterByOrFromOrSelects = new LinkedList<Boolean>();int indent = 1;StringBuffer result = new StringBuffer();StringTokenizer tokens;public FormatProcess(String sql) {this.tokens = new StringTokenizer(sql, "()+*/-=<>'`\"[], \n\r\f\t", true);}public String perform() {this.result.append("\n ");while (this.tokens.hasMoreTokens()) {this.token = this.tokens.nextToken();this.lcToken = this.token.toLowerCase();if ("'".equals(this.token)) {String t;do {t = this.tokens.nextToken();this.token += t;} while ((!"'".equals(t)) && (this.tokens.hasMoreTokens()));} else if ("\"".equals(this.token)) {String t;do {t = this.tokens.nextToken();this.token += t;} while (!"\"".equals(t));}if ((this.afterByOrSetOrFromOrSelect) && (",".equals(this.token))) {commaAfterByOrFromOrSelect();} else if ((this.afterOn) && (",".equals(this.token))) {commaAfterOn();} else if ("(".equals(this.token)) {openParen();} else if (")".equals(this.token)) {closeParen();} else if (BasicFormatterImpl.BEGIN_CLAUSES.contains(this.lcToken)) { beginNewClause();} else if (BasicFormatterImpl.END_CLAUSES.contains(this.lcToken)) { endNewClause();} else if ("select".equals(this.lcToken)) {select();} else if (BasicFormatterImpl.DML.contains(this.lcToken)) {updateOrInsertOrDelete();} else if ("values".equals(this.lcToken)) {values();} else if ("on".equals(this.lcToken)) {on();} else if ((this.afterBetween) && (this.lcToken.equals("and"))) {misc();this.afterBetween = false;} else if (BasicFormatterImpl.LOGICAL.contains(this.lcToken)) {logical();} else if (isWhitespace(this.token)) {white();} else {misc();}if (!isWhitespace(this.token)) {stToken = this.lcToken;}}return this.result.toString();}private void commaAfterOn() {out();this.indent -= 1;newline();this.afterOn = false;this.afterByOrSetOrFromOrSelect = true;}private void commaAfterByOrFromOrSelect() {out();newline();}private void logical() {if ("end".equals(this.lcToken)) {this.indent -= 1;}this.beginLine = false;}private void on() {this.indent += 1;this.afterOn = true;newline();out();this.beginLine = false;}private void misc() {out();if ("between".equals(this.lcToken)) {this.afterBetween = true;}if (this.afterInsert) {newline();this.afterInsert = false;} else {this.beginLine = false;if ("case".equals(this.lcToken))this.indent += 1;}}private void white() {if (!this.beginLine)this.result.append(" ");}private void updateOrInsertOrDelete() {out();this.indent += 1;this.beginLine = false;if ("update".equals(this.lcToken)) {newline();}if ("insert".equals(this.lcToken))this.afterInsert = true;}private void select() {out();this.indent += 1;newline();this.parenCounts.addLast(new Integer(this.parensSinceSelect));this.afterByOrFromOrSelects.addLast(Boolean.valueOf(this.afterByOrSetOrFromOrSelect)); this.parensSinceSelect = 0;this.afterByOrSetOrFromOrSelect = true;}private void out() {this.result.append(this.token);}private void endNewClause() {if (!this.afterBeginBeforeEnd) {this.indent -= 1;if (this.afterOn) {this.indent -= 1;this.afterOn = false;}newline();}out();if (!"union".equals(this.lcToken)) {this.indent += 1;}newline();this.afterBeginBeforeEnd = false;this.afterByOrSetOrFromOrSelect = (("by".equals(this.lcToken)) || ("set".equals(this.lcToken)) || ("from".equals(this.lcToken)));}private void beginNewClause() {if (!this.afterBeginBeforeEnd) {if (this.afterOn) {this.indent -= 1;this.afterOn = false;}this.indent -= 1;out();this.beginLine = false;this.afterBeginBeforeEnd = true;}private void values() {this.indent -= 1;newline();out();this.indent += 1;newline();this.afterValues = true;}private void closeParen() {this.parensSinceSelect -= 1;if (this.parensSinceSelect < 0) {this.indent -= 1;this.parensSinceSelect = ((Integer) this.parenCounts.removeLast()).intValue();this.afterByOrSetOrFromOrSelect = ((Boolean) this.afterByOrFromOrSelects.removeLast()).booleanValue();}if (this.inFunction > 0) {this.inFunction -= 1;out();} else {if (!this.afterByOrSetOrFromOrSelect) {this.indent -= 1;newline();}out();}this.beginLine = false;}private void openParen() {if ((isFunctionName(stToken)) || (this.inFunction > 0)) {this.inFunction += 1;}this.beginLine = false;if (this.inFunction > 0) {out();} else {out();if (!this.afterByOrSetOrFromOrSelect) {this.indent += 1;newline();this.beginLine = true;}}this.parensSinceSelect += 1;}private static boolean isFunctionName(String tok) {char begin = tok.charAt(0);boolean isIdentifier = (Character.isJavaIdentifierStart(begin)) || ('"' == begin);return (isIdentifier) && (!BasicFormatterImpl.LOGICAL.contains(tok))&& (!BasicFormatterImpl.END_CLAUSES.contains(tok))&& (!BasicFormatterImpl.QUANTIFIERS.contains(tok)) && (!BasicFormatterImpl.DML.contains(tok))&& (!BasicFormatterImpl.MISC.contains(tok));}private static boolean isWhitespace(String token) {return " \n\r\f\t".indexOf(token) >= 0;}private void newline() {this.result.append("\n");for (int i = 0; i < this.indent; i++) {this.result.append(" ");}this.beginLine = true;}}public static void main(String[] args) {System.out.println(new BasicFormatterImpl().format("select aa,bb,cc,dd from ta1,(select ee,ff,gg from ta2 where ee=ff) ta3 where aa=bb and cc=dd group by dd order by createtime desc limit 3 ")); }}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
【⒈连接SQLServer数据库】package db;import java.sql.*;import java.util.*;import entity.Student;public class DBUtil {private Connection con;private PreparedStatement pstmt;private ResultSet rs;private String sql;//连接并且查询数据public ArrayList selectAllStudent(){sql = "select * from student";ArrayList arr = new ArrayList();try {Class.forName("com.microsoft.sqlserver.jdbc.SQ LServerDriver");con = DriverManager.getConnection("jdbc:sqlserver://loc alhost:1433;databasename=myschool", "sa", "");pstmt = con.prepareStatement(sql);rs = pstmt.executeQuery();while(rs.next()){Student s = new Student(rs.getInt("id"),rs.getString("name"),rs.getString("sex"));arr.add(s);}return arr;} catch (ClassNotFoundException e) {e.printStackTrace();return null;}catch (SQLException e) {e.printStackTrace();return null;}finally{try {if(rs!=null)rs.close();if(pstmt != null)pstmt.close();if(con!=null && !con.isClosed())con.close();}catch (SQLException e) {e.printStackTrace();}}}//连接并且插入数据public int insertStudent(Student s){sql ="insert into student(name,sex) values(?,?)";try {Class.forName("com.microsoft.sqlserver.jdbc.SQL ServerDriver");con = DriverManager.getConnection("jdbc:sqlserver://loc alhost:1433;databasename=myschool","sa", "");pstmt = con.prepareStatement(sql);pstmt.setString(1,s.getName());pstmt.setString(2,s.getSex());return pstmt.executeUpdate();}catch (ClassNotFoundException e) {e.printStackTrace();return 0;}catch (SQLException e) {e.printStackTrace();return 0;}finally{try {if(pstmt != null)pstmt.close();if(con!=null && !con.isClosed())con.close();}catch (SQLException e) {e.printStackTrace();}}}//连接并且删除数据public int deleteStudentById(int id){sql ="delete from student where id=?";try {Class.forName("com.microsoft.sqlserver.jdbc.SQ LServerDriver");con = DriverManager.getConnection("jdbc:sqlserver://loc alhost:1433;databasename=myschool","sa", "");pstmt = con.prepareStatement(sql);pstmt.setInt(1,id);return pstmt.executeUpdate();}catch (ClassNotFoundException e) {e.printStackTrace();return 0;}catch (SQLException e) {e.printStackTrace();return 0;}finally{try {if(pstmt != null)pstmt.close();if(con!=null && !con.isClosed())con.close();}catch (SQLException e) {e.printStackTrace();}}}//连接并且更新数据public int updateStudent(Student s){sql ="update student set name=?,sex=? where id=?"; try {Class.forName("com.microsoft.sqlserver.jdbc.S QLServerDriver");con = DriverManager.getConnection("jdbc:sqlserver://loc alhost:1433;databasename=myschool","sa", "");pstmt = con.prepareStatement(sql);pstmt.setString(1,s.getName());pstmt.setString(2,s.getSex());pstmt.setInt(3,s.getId());return pstmt.executeUpdate();} catch (ClassNotFoundException e) {e.printStackTrace();return 0;} catch (SQLException e) {e.printStackTrace();return 0;}finally{try {if(pstmt != null)pstmt.close();if(con!=null && !con.isClosed())con.close();} catch (SQLException e) {e.printStackTrace();}}}}【⒉模拟数据库中的数据并创建一实体个类entity】package entity;public class Student {private int id;private String name;private String sex;public Student() {super();}public Student(int id, String name, String sex) {super();this.id = id; = name;this.sex = sex;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}}【⒊创建测试类】1创建一个SelectTest查询类:package test;import java.util.ArrayList;import db.DBUtil;import entity.Student;public class SelectTest {/*** @param args*/public static void main(String[] args) {DBUtil db = new DBUtil();ArrayList arr = db.selectAllStudent();for(int i=0;i<arr.size();i++){Student s = (Student)arr.get(i);System.out.println(s.getId()+s.getName()+s.getS ex());}}}2创建一个insertTest插入类package test;import java.util.Scanner;import db.DBUtil;import entity.Student;public class insertTest {/*** @param args*/public static void main(String[] args) {DBUtil db = new DBUtil();Scanner input = new Scanner(System.in); System.out.print("please input name:");String name = input.next();System.out.print("please input sex:");String sex = input.next();Student s = new Student();s.setName(name);s.setSex(sex);int re = db.insertStudent(s);if(re == 1)System.out.println("插入成功");else{System.out.println("插入失败");}}}3创建一个DeleteTest删除数据类:package test;import db.DBUtil;public class DeleteTest {/*** @param args*/public static void main(String[] args) {DBUtil db = new DBUtil();int re = db.deleteStudentById(3);if(re == 1)System.out.println("删除成功");else{System.out.println("删除失败");}}}4创建一个UpdateTest数据更新类: package test;import db.DBUtil;import entity.Student;public class UpdateTest {/*** @param args*/public static void main(String[] args) { DBUtil db= new DBUtil();Student s = new Student(2,"ttttttttt","xxxx"); int re = db.updateStudent(s);if(re == 1)System.out.println("更新成功");else{System.out.println("更新失败");}}}。