java Mysql参数化查询

如题,我想在servlet的doGet函数里写从MySQL数据库中读取数据,查询语句不能拼字符串,要用参数化的方式,求这一流程的代码,学习完了马上就能用到。

1个回答

参数化查询,难道不是PreparedStatement吗?你试试

Mr_Megamind
IMplementist 虽然是一年前的问题,而且当时根本不知道你在说什么,但是现在学会了之后,再上CSDN发现你说的算是对的,采纳啦!
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
急急急,请教JSP如何调用数据库mysql的java文件。
各位好,我实在是菜鸟,在网上找个JAVA文件,连接mysql数据库,经过测试,已经成功,现在用JSP页面来调用,就是不通过,真心请各位指点,急急急,下面把JAVA文件和JSP页面发出来,小弟谢过! JAVA文件 import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Connection; import java.sql.Statement; public class DB { public static void main(String[] args) throws Exception { Connection conn = null; String sql; // MySQL的JDBC URL编写方式:jdbc:mysql://主机名称:连接端口/数据库的名称?参数=值 // 避免中文乱码要指定useUnicode和characterEncoding // 执行数据库操作之前要在数据库管理系统上创建一个数据库,名字自己定, // 下面语句之前就要先创建javademo数据库 String url = "jdbc:mysql://localhost:3306/数据库名字?" + "user=数据库用户名&password=数据库密码&useUnicode=true&characterEncoding=UTF8"; try { // 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来, // 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来,下面三种形式都可以 Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动 // or: // com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver(); // or: // new com.mysql.jdbc.Driver(); System.out.println("成功加载MySQL驱动程序"); // 一个Connection代表一个数据库连接 conn = DriverManager.getConnection(url); // Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等 Statement stmt = conn.createStatement(); sql = "create table student(NO char(20),name varchar(20),primary key(NO))"; int result = stmt.executeUpdate(sql);// executeUpdate语句会返回一个受影响的行数,如果返回-1就没有成功 if (result != -1) { System.out.println("创建数据表成功"); sql = "insert into student(NO,name) values('2012001','陶伟基')"; result = stmt.executeUpdate(sql); sql = "insert into student(NO,name) values('2012002','周小俊')"; result = stmt.executeUpdate(sql); sql = "select * from student"; ResultSet rs = stmt.executeQuery(sql);// executeQuery会返回结果的集合,否则返回空值 System.out.println("学号\t姓名"); while (rs.next()) { System.out .println(rs.getString(1) + "\t" + rs.getString(2));// 入如果返回的是int类型可以用getInt() } } } catch (SQLException e) { System.out.println("MySQL操作错误"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { conn.close(); } } } JSP页面 <%@ page contentType="text/html;charset=gb2312" %> <%@ page import="java.sql.*" %> <%@ page import="java.util.*"%> <%@ page import="org.cmcc.databaseconnection.*"%> <% request.setCharacterEncoding("utf-8"); %> <% DB conn=new DB(); Statement stmt = conn.createStatement(); String str1 = "select * from yh"; ResultSet result=stmt.executeQuery(str1); if(result.next()) { %> <%=result.getString(2)%>; <% } else { %> <script language="javascript"> alert("XX"); history.back(); </script> <% } %>
java与mysql的连接错误
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) 这错误到底怎么改啊?本人还是菜鸟,希望大家能说得详细一点,谢谢啦!! package com.jingxin.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class JDBCText { public static void main(String[] args) { String sql="SELET * FROM tbl_user"; Connection conn=null; Statement st=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver");//注册JDBC驱动程序,forname用来初始化参数指定的类,并创建一个指定的实例对象。 String url = "jdbc:mysql://127.0.0.1:3306/testdb?" + "user=root&password=123456&useUnicode=true&characterEncoding=UTF8"; conn = DriverManager.getConnection(url); st=conn.createStatement(); rs=st.executeQuery(sql);//发送sql语句 /*对ResultSet对象进行遍历*/ while(rs.next()){ System.out.println(rs.getInt("id")+" ");//用来获取数据库中字段类型为整型的字段值。 System.out.println(rs.getString("name")+" "); System.out.println(rs.getString("password")+" "); System.out.println(rs.getString("email")+" "); System.out.println(); } } catch (Exception e) { e.printStackTrace(); }finally{ try { rs.close(); } catch (Exception e2) { // TODO: handle exception } try { st.close(); } catch (Exception e2) { // TODO: handle exception } try { conn.close(); } catch (Exception e2) { // TODO: handle exception } } } }
基于springmvc+mybatis的登录表单提交后404
前端填写正确的用户名和密码后,提交登录,浏览器显示404,前端提交的地址是/userlogin,后端对接的/user/userlogin也是对的,浏览器f12里显示请求的确成功传给了后端,但是不知道为什么404。用的是tomcat8.5,java版本1.8,phpstudy最新版,mysql5.7.26。 ## 这是所用到的包: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567617_880785.jpg) ## 这是目录结构: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567511_223692.jpg) ## 这是web.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc_test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/context-config.xml</param-value> </context-param> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- DispatcherServlet在初始化方法里面会读取该初始化参数的值来获得 spring配置文件的位置 ,然后启动spring容器。 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置字符编码 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` ## 这是context-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描service包下的注解 --> <context:component-scan base-package="com.test.service"></context:component-scan> <!-- 配置数据库 --> <!-- 加载配置文件 --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/Eday_Test"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- 配置Sqlsessionfactory并将数据源注入 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引入数据源 --> <property name="dateSource" ref="dateSource"></property> <!-- 载入mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 载入配置mapper映射的xml --> <property name="mapperLocations" value="classpath:com/test/mapper/*.xml"></property> </bean> <!-- 配置扫描mapper接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackge" value="com.test.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dateSource" ref="dateSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` ## 这是mybatis-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <!-- 配置别名 --> <typeAlias alias="User" type="com.test.pojo.User"/> </typeAliases> </configuration> ``` ## 这是springmvc-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描controller包下的注解 --> <context:component-scan base-package="com.test.controller"></context:component-scan> <!-- 开启注解 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 静态资源访问 --> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置试图解析的默认路径,即配置页面的根路径 --> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` ## 这是UserController.java: ```java package com.test.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.test.pojo.User; import com.test.service.UserService; //声明控制器 @Controller //设置bean的scope属性为多例(prototype) @Scope("prototype") //设置请求映射,当客户端请求/user时,转到该控制器处理 @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value="/userlogin") public ModelAndView login(String user_Name,String user_pwd,ModelAndView mv,HttpSession session){ //调用userService中的login方法处理user实体类对象 User user = userService.login(user_Name,user_pwd); //登录的逻辑判断,判断条件是返回结果不为空 if(user!=null){ //登陆成功,将user对象设置到HttpSession作用范围域中,相当于服务端的cookie,有效时间默认30分钟 //在程序运行期间,在任意页面都可以提取它的值。 session.setAttribute("user",user); //转发到main请求 //登录成功,跳转页面 mv.setViewName("login/login-success"); }else{ //登录失败,向前端传递失败信息 mv.addObject("message","用户名或密码错误,请重新输入!"); //登录失败,跳转到登录页面 mv.setViewName("login"); } return mv; } //跳转到用户注册界面 @RequestMapping(value="/userregister"/*,method=RequestMethod.POST*/) public String register(User user){ String user_Name = user.getUser_Name(); //如果数据库中没有该用户,可以注册,否则跳转页面 if(userService.findByUserName(user_Name)==null){ //添加用户 userService.register(user); //注册成功,跳转到主页面 return "index"; }else{ //注册失败,跳转到错误页面 return "error"; } } } ``` ## 这是UserMapper.java: ```java package com.test.mapper; import org.apache.ibatis.annotations.Param; import com.test.pojo.User; public interface UserMapper { //根据用户名和密码查找,mybatis中有多个参数时,需要使用@Param注解 User findByUserNameAndPassword(@Param("user_Name")String user_Name,@Param("user_Pwd")String user_Pwd); //增加用户 void addUser(User user); //根据用户名查询 User findByUserName(String user_Name); } ``` ## 这是UserMapper.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.tes.mapper.UserMapper"> <!-- 根据用户名和密码查询 --> <select id="findByUserNameAndPasssword" resultType="User"> select * from user where user_Name=#{user_Name} and user_Pwd=#{user_Pwd} </select> <!-- 增加用户 --> <insert id="addUser" parameterType="User"> insert into user (user_Name,user_Pwd,user_Email,user_NickName,user_Birth,user_Phone,user_InvitationCode) values(#{user_Name},#{user_Pwd},#{user_Email},#{user_NickName},#{user_Birth},#{user_Phone},#{user_InvitationCode}) </insert> <!-- 根据用户名查询 --> <select id="findByUserName" resultType="User"> select * from user where user_Name=#{user_Name} </select> </mapper> ``` ## 这是User.java: ```java package com.test.pojo; import java.sql.Timestamp; public class User { private int user_Id; private String user_Name; private int user_Pwd; private String user_Email; private String user_NickName; private Timestamp user_Time; private String user_Birth; private int user_Fans; private int user_Follow; private int user_Score; private String user_HeadImgAddr; private int user_Phone; private String user_InvitationCode; public int getUser_Id() { return user_Id; } public void setUser_Id(int user_Id) { this.user_Id = user_Id; } public String getUser_Name() { return user_Name; } public void setUser_Name(String user_Name) { this.user_Name = user_Name; } public int getUser_Pwd() { return user_Pwd; } public void setUser_Pwd(int user_Pwd) { this.user_Pwd = user_Pwd; } public String getUser_Email() { return user_Email; } public void setUser_Email(String user_Email) { this.user_Email = user_Email; } public String getUser_NickName() { return user_NickName; } public void setUser_NickName(String user_NickName) { this.user_NickName = user_NickName; } public Timestamp getUser_Time() { return user_Time; } public void setUser_Time(Timestamp user_Time) { this.user_Time = user_Time; } public String getUser_Birth() { return user_Birth; } public void setUser_Birth(String user_Birth) { this.user_Birth = user_Birth; } public int getUser_Fans() { return user_Fans; } public void setUser_Fans(int user_Fans) { this.user_Fans = user_Fans; } public int getUser_Follow() { return user_Follow; } public void setUser_Follow(int user_Follow) { this.user_Follow = user_Follow; } public int getUser_Score() { return user_Score; } public void setUser_Score(int user_Score) { this.user_Score = user_Score; } public String getUser_HeadImgAddr() { return user_HeadImgAddr; } public void setUser_HeadImgAddr(String user_HeadImgAddr) { this.user_HeadImgAddr = user_HeadImgAddr; } public int getUser_Phone() { return user_Phone; } public void setUser_Phone(int user_Phone) { this.user_Phone = user_Phone; } public String getUser_InvitationCode() { return user_InvitationCode; } public void setUser_InvitationCode(String user_InvitationCode) { this.user_InvitationCode = user_InvitationCode; } @Override public String toString() { return "User [user_Id=" + user_Id + ", user_Name=" + user_Name + ", user_Pwd=" + user_Pwd + ", user_Email=" + user_Email + ", user_NickName=" + user_NickName + ", user_Time=" + user_Time + ", user_Birth=" + user_Birth + ", user_Fans=" + user_Fans + ", user_Follow=" + user_Follow + ", user_Score=" + user_Score + ", user_HeadImgAddr=" + user_HeadImgAddr + ", user_Phone=" + user_Phone + ", user_InvitationCode=" + user_InvitationCode + "]"; } } ``` ## 这是UserService.java: ```java package com.test.service; import com.test.pojo.User; public interface UserService { //通过用户名及密码核查用户登录 User login(String user_Name,String user_Pwd); //增加用户 void register(User user); //根据用户名查询 User findByUserName(String user); } ``` ## 这是UserServiceImpl.java: ```java package com.test.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.test.mapper.UserMapper; import com.test.pojo.User; import com.test.service.UserService; @Service @Transactional public class UserServiceImpl implements UserService { //注入UserMapper接口 @Autowired private UserMapper userMapper; //登录,根据用户名和密码进行查询 @Override public User login(String user_Name,String user_Pwd){ return userMapper.findByUserNameAndPassword(user_Name,user_Pwd); } //注册,增加用户 @Override public void register(User user){ userMapper.addUser(user); } //根据用户名查询 @Override public User findByUserName(String user_Name){ return userMapper.findByUserName(user_Name); } } ``` ##这是login.jsp ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/login.css" /> <title>登录</title> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <!--登录板块--> <header class="header"> <p class="logintitle"> <b>登录</b> </p> <form action="${pageContext.request.contextPath }/user/userlogin" method="post" class=login-form> <p class= login-username-p> <label for="username" class="login-username-text">用户名:</label> <input type=text name="user_Name" class="login-username-input"> <br><a href="register.jsp" class=login-register>注册</a> </p> <p class="login-psw-p"> <label for="psw" class="login-psw-text">密码:</label> <input type=password name="user_Pwd" class="login-psw-input"> <br><a href="#" class=login-forget>忘记密码</a> </p> <div class=login-button-div> <label for=button></label> <button type=sublim class=login-button>登录</button> </div> </form> </header> </body> </html> ``` ## 这是login-success.jsp: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录成功,请等待跳转...</title> <script type="text/javascript"> onload=function(){ setInterval(go, 1000); }; var x=3; //利用了全局变量来执行 function go(){ x--; if(x>0){ document.getElementById("sp").innerHTML=x; //每次设置的x的值都不一样了。 }else{ location.href='../index.jsp'; } } </script> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <header> <div> <p>登录成功!页面将在3秒后自动跳转,请稍等...</p> </div> </header> </body> </html> ``` ## 这是数据库: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580568589_694404.jpg)
在线等!!!linux服务器连接mysql5.7数据库报错 Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException
以下是服务器上的报错代码 ![图片说明](https://img-ask.csdn.net/upload/201911/12/1573526989_375593.png) ``` >org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 500, creating 1 ``` 问题就是出在这里. 1,本地项目正常启动,无任何报错,数据库连接正常(使用的都是linux上面的数据库). ![图片说明](https://img-ask.csdn.net/upload/201911/12/1573527132_402324.png) 2,数据库工具使用无任何问题 ![图片说明](https://img-ask.csdn.net/upload/201911/12/1573527246_699888.png) 3,下面放出jdbc配置文件和spring配置文件 ``` jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://..XXXXXX.:/XXXXXX?useUnicode=true&characterEncoding=UTF-8&useSSL=false jdbc.username=xxxx jdbc.password=xxxxx jdbc.filters=stat jdbc.maxActive=500 jdbc.initialSize=1 jdbc.maxWait=1000 jdbc.minIdle=10 jdbc.maxIdle=15 jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.minEvictableIdleTimeMillis=300000 jdbc.validationQuery=SELECT 'x' jdbc.testWhileIdle=true jdbc.testOnBorrow=false jdbc.testOnReturn=false jdbc.maxOpenPreparedStatements=20 jdbc.removeAbandoned=true jdbc.removeAbandonedTimeout=180 jdbc.logAbandoned=true ``` spring 配置 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="com.yoFish.service"/> <!-- 配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 阿里 druid 数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <!-- 数据库基本信息配置 --> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="filters" value="${jdbc.filters}"/> <!-- 最大并发连接数 --> <property name="maxActive" value="${jdbc.maxActive}"/> <!-- 初始化连接数量 --> <property name="initialSize" value="${jdbc.initialSize}"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${jdbc.maxWait}"/> <!-- 最小空闲连接数 --> <property name="minIdle" value="${jdbc.minIdle}"/> <!-- 最大空闲连接数 --> <property name="maxIdle" value="${jdbc.maxIdle}"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/> <property name="validationQuery" value="${jdbc.validationQuery}"/> <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/> <property name="testOnBorrow" value="${jdbc.testOnBorrow}"/> <property name="testOnReturn" value="${jdbc.testOnReturn}"/> <property name="maxOpenPreparedStatements" value="${jdbc.maxOpenPreparedStatements}"/> <!-- 超过时间限制是否回收 --> <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/> <!-- 1800 秒,也就是 30 分钟 --> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/> <!-- 关闭 abanded 连接时输出错误日志 --> <property name="logAbandoned" value="${jdbc.logAbandoned}"/> </bean> <!-- 配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 扫描model包 使用别名 --> <property name="typeAliasesPackage" value="com.yoFish.model"/> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.yoFish.dao"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` 这个问题搞了很久了,主要就是不知道问题在哪,本地真的是没有任何问题,很多方式我也试过了.很头疼,求大佬帮忙解决
求助!!!http500的问题
主要的问题是希望有高手能解答一下,谢谢了。最好能快一点和通俗一点。 <!-- 配置数据源 -使用c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver" /><!-- 数据库驱动 --> <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/depot" /> <!-- 连接URL --> <property name="user" value="root" /> <!-- 数据库用户名 --> <property name="password" value="123456" /> <!-- 数据库密码 --> <!-- c3p0连接池参数配置 --> <property name="initialPoolSize" value="3" /><!-- 初始化连接数 --> <property name="minPoolSize" value="2" /><!-- 最小连接数 --> <property name="maxPoolSize" value="10" /><!-- 连接池中保留的最大连接数 --> <property name="maxIdleTime" value="28000" /><!-- 连接的过期时间(秒) --> <property name="idleConnectionTestPeriod" value="3600" /><!-- 检查连接池中的空闲连接间隔时间(秒) --> </bean> 这是数据库连接 数据库的url是 jdbc:mysql://127.0.0.1:3306/Mysql 报错的全部信息在这里。 HTTP Status 500 - Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection 。 type Exception report message Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection description The server encountered an internal error that prevented it from fulfilling this request. exception org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) com.service.UserService$$EnhancerBySpringCGLIB$$49abd10c.getUser(<generated>) com.action.UserAction.login(UserAction.java:42) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:894) ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539) ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68) com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96) com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88) ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1615) ognl.ASTMethod.getValueBody(ASTMethod.java:91) ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212) ognl.SimpleNode.getValue(SimpleNode.java:258) ognl.Ognl.getValue(Ognl.java:467) ognl.Ognl.getValue(Ognl.java:431) com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:351) com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:403) com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:349) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:177) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:73) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:192) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:155) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:120) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:195) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:54) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:564) org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81) org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143) root cause org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47) org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97) org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:102) org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129) org.hibernate.internal.SessionImpl.connection(SessionImpl.java:514) org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:448) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) com.service.UserService$$EnhancerBySpringCGLIB$$49abd10c.getUser(<generated>) com.action.UserAction.login(UserAction.java:42) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:894) ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539) ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68) com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96) com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88) ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1615) ognl.ASTMethod.getValueBody(ASTMethod.java:91) ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212) ognl.SimpleNode.getValue(SimpleNode.java:258) ognl.Ognl.getValue(Ognl.java:467) ognl.Ognl.getValue(Ognl.java:431) com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:351) com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:403) com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:349) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:177) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:73) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:192) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:155) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:120) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:195) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:54) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:564) org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81) org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143) root cause java.sql.SQLException: Connections could not be acquired from the underlying database! com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:692) com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140) org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35) org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99) org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129) org.hibernate.internal.SessionImpl.connection(SessionImpl.java:514) org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:448) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) com.service.UserService$$EnhancerBySpringCGLIB$$49abd10c.getUser(<generated>) com.action.UserAction.login(UserAction.java:42) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:894) ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539) ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68) com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96) com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88) ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1615) ognl.ASTMethod.getValueBody(ASTMethod.java:91) ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212) ognl.SimpleNode.getValue(SimpleNode.java:258) ognl.Ognl.getValue(Ognl.java:467) ognl.Ognl.getValue(Ognl.java:431) com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:351) com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:403) com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:349) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:177) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:73) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:192) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:155) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:120) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:195) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:54) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:564) org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81) org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143) root cause com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source. com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1469) com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:644) com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:554) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:758) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:685) com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140) org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35) org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99) org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129) org.hibernate.internal.SessionImpl.connection(SessionImpl.java:514) org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:448) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) com.service.UserService$$EnhancerBySpringCGLIB$$49abd10c.getUser(<generated>) com.action.UserAction.login(UserAction.java:42) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:894) ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539) ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68) com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96) com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88) ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1615) ognl.ASTMethod.getValueBody(ASTMethod.java:91) ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212) ognl.SimpleNode.getValue(SimpleNode.java:258) ognl.Ognl.getValue(Ognl.java:467) ognl.Ognl.getValue(Ognl.java:431) com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:351) com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:403) com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:349) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:177) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:73) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:192) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:155) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:120) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:195) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247) org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:54) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:564) org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81) org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143) root cause java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:127) com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95) com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:87) com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:61) com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:71) com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862) com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:444) com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230) com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226) com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175) com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220) com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203) com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138) com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125) com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44) com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870) com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) root cause com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. sun.reflect.GeneratedConstructorAccessor45.newInstance(Unknown Source) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:423) com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:59) com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:83) com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:128) com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2201) com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2225) com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1391) com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:993) com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:852) com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:444) com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230) com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226) com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175) com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220) com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203) com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138) com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125) com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44) com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870) com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) note The full stack trace of the root cause is available in the Apache Tomcat/8.5.9 logs. 是从论坛上下下来的求助挺紧的26号上午就要用 是一个有关jsp和mysql数据库的仓储管理系统我用的是myeclipsi2017 和mysql8.0 tomcat8.5
要求上传的参数类型是 byte[]jsondata,怎么转?
让我根据接口文档的要求在数据库中抽取数据,然后调用webServer接口将数据上传。接口要求 数据在组织时,以json格式组织。就是byte[] jsonData。 我的把抽出来的数据转成json然后存jsonarray里了,现在怎么转成byte[]jsonData 求指教!!!! ``` private int uploadDataType_1() throws SQLException{ //获取数据 int start = 1;//开始记录索引位置 int pageSize = 20;//页大小(每页显示条数即一次查询多少条数据) int SJpageSize =20 ;//实际当前页的数据量 int responseCode=0;//初始化返回值 int n = 0;//测试 int m =0; while (SJpageSize==20) { String sql = "select * from (select *, ROW_NUMBER() OVER(Order by id ) AS RowId from TB_StoreHouse ) as b where RowId between "+ start +" and "+ pageSize ; ResultSet resultSet = DBConnection.executeQuery(sql); start+=20; pageSize+=20; //数据集结构 ResultSetMetaData reMetaData = resultSet.getMetaData(); //数据集的列数 int columnCount = reMetaData.getColumnCount(); JSONArray array = new JSONArray(); SJpageSize=0; while ( resultSet.next()) { //转json JSONObject jsonObject = new JSONObject(); for (int i = 1; i <= columnCount; i++) { String columnLabel = reMetaData.getColumnLabel(i); String value = resultSet.getString(columnLabel); jsonObject.put(columnLabel, value); } ++SJpageSize; array.add(jsonObject); } System.out.println(array); GrainServiceImplService rs = new GrainServiceImplService(); GrainService re = rs.getGrainServiceImplPort(); responseCode=re.test(array, "1", 1, "3", "4"); m +=SJpageSize; System.out.println("当前第"+ ++n+"页,有"+SJpageSize+"条,已上传"+m+"条"); } return responseCode; ``` responseCode=re.test(array, "1", 1, "3", "4"); --报错要求第一个参数是byte[]jsonData
java.sql.SQLException错误
运行StuDialog.class出现下面错误提示,初学Java请求帮助找出下面是什么原因? java.sql.SQLException: No value specified for parameter 2 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929) at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2560) at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2536) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2383) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2327) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2312) at com.studentmanager.StuAddDialog.actionPerformed(StuAddDialog.java:109) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6216) at javax.swing.JComponent.processMouseEvent(JComponent.java:3265) at java.awt.Component.processEvent(Component.java:5981) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4583) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4413) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4556) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4220) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4150) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2475) at java.awt.Component.dispatchEvent(Component.java:4413) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178) at java.awt.Dialog$1.run(Dialog.java:1051) at java.awt.Dialog$3.run(Dialog.java:1103) at java.security.AccessController.doPrivileged(Native Method) at java.awt.Dialog.show(Dialog.java:1101) at java.awt.Component.show(Component.java:1516) at java.awt.Component.setVisible(Component.java:1468) at java.awt.Window.setVisible(Window.java:841) at java.awt.Dialog.setVisible(Dialog.java:991) at com.studentmanager.StuAddDialog.<init>(StuAddDialog.java:73) at com.studentmanager.StuDialog.actionPerformed(StuDialog.java:109) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6216) at javax.swing.JComponent.processMouseEvent(JComponent.java:3265) at java.awt.Component.processEvent(Component.java:5981) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4583) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4413) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4556) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4220) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4150) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2475) at java.awt.Component.dispatchEvent(Component.java:4413) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) 1、StuDialog.class如下: package com.studentmanager; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; public class StuDialog extends JFrame implements ActionListener{ //定义一些控件 JPanel jp1,jp2; JLabel jl1; JButton jb1,jb2,jb3,jb4; JTable jt; JScrollPane jsp; JTextField jtf; public static void main(String[] args) { // TODO Auto-generated method stub StuDialog stuDialog=new StuDialog(); } public StuDialog() { jp1=new JPanel(); jtf=new JTextField(10); jb1=new JButton("查询"); jb1.addActionListener(this); jl1=new JLabel("请输入名字"); //把各个控件加入到jp1 jp1.add(jl1); jp1.add(jtf); jp1.add(jb1); jp2=new JPanel(); jb2=new JButton("添加"); jb2.addActionListener(this); jb3=new JButton("修改"); jb4=new JButton("删除"); //把各个按钮就加入到jp2 jp2.add(jb2); jp2.add(jb3); jp2.add(jb4); /*//rowData可以存放多行 Vector hang=new Vector(); hang.add("sp001"); hang.add("孙悟空"); hang.add("男"); hang.add("25"); hang.add("火锅山"); hang.add("少林派"); //加入到rowData rowData.add(hang);*/ //创建一个数据模型对象 StuModel sm=new StuModel(); //初始化JTable jt=new JTable(sm); //初始化Jsp JScrollPane jsp=new JScrollPane(jt); //把jsp放入JFrame this.add(jsp); this.add(jp1,"North"); this.add(jp2,"South"); this.setSize(400,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //判断是哪个按钮被点击 if(e.getSource()==jb1) { System.out.println("用户想查询"); //因为把表的现实的数据封装到StuModel中,那么我们就可以 //简单完成查询 //查询数据库,更新JTable String name=this.jtf.getText().trim(); //写一个SQL语句 String sql="select * from stu where stuName='"+name+"'"; //构建新的数据模型,并更新 StuModel sm=new StuModel(sql); //更新JTable jt.setModel(sm); //当用户点击添加 } else if(e.getSource()==jb2) { StuAddDialog sa=new StuAddDialog(this,"添加学生",true); //重新再获得新的数据模型 } } } 2、StuAddDialog.class如下: package com.studentmanager; import java.awt.*; import javax.swing.*; import java.util.*; import java.awt.event.*; import javax.swing.JDialog; import java.sql.*; public class StuAddDialog extends JDialog implements ActionListener { //定义我需要的swing控件 JPanel jp1,jp2,jp3; JTextField jtf1,jtf2,jtf3,jtf4,jtf5,jtf6; JButton jb1,jb2; JLabel jl1,jl2,jl3,jl4,jl5,jl6; //owner 它的父窗口 //title窗口名 //model指定是模式窗口,还是非模式窗口 public StuAddDialog(Frame owner,String title,boolean modal) { super(owner,title,modal);//调用父类构造方法,达到模式对话框效果 jl1=new JLabel("学号"); jl2=new JLabel("姓名"); jl3=new JLabel("性别"); jl4=new JLabel("年龄"); jl5=new JLabel("籍贯"); jl6=new JLabel("系别"); jtf1=new JTextField(); jtf2=new JTextField(); jtf3=new JTextField(); jtf4=new JTextField(); jtf5=new JTextField(); jtf6=new JTextField(); jb1=new JButton("添加"); jb1.addActionListener(this); jb2=new JButton("取消"); jp1=new JPanel(); jp2=new JPanel(); jp3=new JPanel(); //设置布局 jp1.setLayout(new GridLayout(6,1)); jp2.setLayout(new GridLayout(6,1)); jp1.add(jl1); jp1.add(jl2); jp1.add(jl3); jp1.add(jl4); jp1.add(jl5); jp1.add(jl6); jp2.add(jtf1); jp2.add(jtf2); jp2.add(jtf3); jp2.add(jtf4); jp2.add(jtf5); jp2.add(jtf6); jp3.add(jb1); jp3.add(jb2); this.add(jp1,BorderLayout.WEST); this.add(jp2,BorderLayout.CENTER); this.add(jp3,BorderLayout.SOUTH); jb1.addActionListener(this); //展现 this.setSize(300,250); //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource()==jb1) { //对用户点击添加按钮后的响应动作 //连接数据库 Connection ct=null; Statement stmt=null; ResultSet rs=null; PreparedStatement psmt=null; //连接数据库,判断用户是否合法 try{ //1加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2创建连接对象,注册驱动程序并打开连接对象 ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=GBK","root","123456"); psmt=ct.prepareStatement("select * from stu"); //3获取语句对象 //stmt=ct.createStatement(); //与编译语句对象 psmt=ct.prepareStatement("insert into stu values(?,?,?,?,?,?)"); //给参数赋值 psmt.setString(1,jtf1.getText()); psmt.setString(1,jtf2.getText()); psmt.setString(1,jtf3.getText()); psmt.setString(1,jtf4.getText()); psmt.setString(1,jtf5.getText()); psmt.setString(1,jtf6.getText()); //4执行操作 psmt.executeUpdate(); this.dispose();//关闭对话框 }catch(ClassNotFoundException e1) { e1.printStackTrace(); }catch(SQLException e2) { e2.printStackTrace(); } finally { //释放语句对象,连接对象 try { if(rs!=null) rs.close(); if(stmt!=null) stmt.close(); if(ct!=null) ct.close(); }catch(Exception e2) { e2.printStackTrace(); } } } } @Override public Container getContentPane() { // TODO Auto-generated method stub return super.getContentPane(); } @Override public void setContentPane(Container contentPane) { // TODO Auto-generated method stub super.setContentPane(contentPane); } }
Mybatis小练习 报错 求大神指导,信息详尽
# UserMapper ``` public interface UserMapper { //根据id查询用户信息 public User findUserById(int id) throws Exception; //根据用户名列查询用户列表 public List<User> findUserByName(String name)throws Exception; //插入用户 public void insertUser(User user)throws Exception; } ``` # UserMapper.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace等于mapper接口地址 --> <mapper namespace="com.neuedu.mapper.UserMapper"> <!-- 在 映射文件中配置很多sql语句 --> <!-- 需求:通过id查询用户表的记录 --> <!-- 通过 select执行数据库查询 id:标识 映射文件中的 sql 将sql语句封装到mappedStatement对象中,所以将id称为statement的id parameterType:指定输入 参数的类型,这里指定int型 #{}表示一个占位符号 #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称 resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。 --> <select id="findUserById" parameterType="int" resultType="user"> SELECT * FROM user WHERE id=#{value} </select> <!-- 根据用户名称模糊查询用户信息,可能返回多条 resultType:指定就是单条记录所映射的java对象 类型 ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。 使用${}拼接sql,引起 sql注入 ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value --> <select id="findUserByName" parameterType="java.lang.String" resultType="com.neuedu.pojo.User"> SELECT * FROM user WHERE username LIKE '%${value}%' </select> <!-- 添加用户 parameterType:指定输入 参数类型是pojo(包括 用户信息) #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值 --> <insert id="insertUser" parameterType="com.neuedu.pojo.User"> <!-- 将插入数据的主键返回,返回到user对象中 SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键 keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性 order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序 resultType:指定SELECT LAST_INSERT_ID()的结果类型 --> insert into user(id,username,birthday,sex,address) values (seq_user.nextval,#{username},#{birthday},#{sex},#{address}) <!-- 插入数据后,返回自动增长列的ID值,将sql语句的返回值赋给parameterType绑定对象的ID属性 MySQL中使用: select LAST_INSERT_ID() --> <selectKey keyProperty="id" order="AFTER" resultType="int"> SELECT LAST_INSERT_ID() <!--select seq_user.currval from dual--> </selectKey> <!-- 使用mysql的uuid()生成主键 执行过程: 首先通过uuid()得到主键,将主键设置到user对象的id属性中 其次在insert执行时,从user对象中取出id属性值 --> <!-- <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String"> SELECT uuid() </selectKey> insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address}) --> </insert> <!-- 删除 用户 根据id删除用户,需要输入 id值 --> <delete id="deleteUser" parameterType="java.lang.Integer"> delete from user where id=#{id} </delete> <!-- 根据id更新用户 分析: 需要传入用户的id 需要传入用户的更新信息 parameterType指定user对象,包括 id和更新信息,注意:id必须存在 #{id}:从输入 user对象中获取id属性值 --> <update id="updateUser" parameterType="com.neuedu.pojo.User"> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} </update> </mapper> ``` # Tset ``` public class UserMapperTest { private SqlSessionFactory sqlSessionFactory; // 此方法是在执行testFindUserById之前执行 @Before public void setUp() throws Exception { // 创建sqlSessionFactory // mybatis配置文件 String resource = "config/SqlMapConfig.xml"; // 得到配置文件流 InputStream inputStream = Resources.getResourceAsStream(resource); // 创建会话工厂,传入mybatis的配置文件信息 sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); } @Test public void testFindUserById() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); //创建UserMapper对象,mybatis自动生成mapper代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //调用userMapper的方法 User user = userMapper.findUserById(1); System.out.println(user); } @Test public void testFindUserByName() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); //创建UserMapper对象,mybatis自动生成mapper代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //调用userMapper的方法 List<User> list = userMapper.findUserByName("袁超"); sqlSession.close(); System.out.println(list); } } ``` # 报错信息 ``` DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. DEBUG [main] - Class not found: org.jboss.vfs.VFS DEBUG [main] - JBoss 6 VFS API is not available in this environment. DEBUG [main] - Class not found: org.jboss.vfs.VirtualFile DEBUG [main] - VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment. DEBUG [main] - Using VFS adapter org.apache.ibatis.io.DefaultVFS DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo DEBUG [main] - Reader entry: User.class DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo/User.class DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo/User.class DEBUG [main] - Reader entry: ���� 1 N DEBUG [main] - Checking to see if class com.neuedu.pojo.User matches criteria [is assignable to Object] DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper DEBUG [main] - Reader entry: UserMapperTest.class DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper/UserMapperTest.class DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper/UserMapperTest.class DEBUG [main] - Reader entry: ���� 1 a DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper DEBUG [main] - Reader entry: UserMapper.class DEBUG [main] - Reader entry: UserMapper.xml DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.class DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.class DEBUG [main] - Reader entry: ���� 1    findUserById (I)Lcom/neuedu/pojo/User; DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.xml DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.xml DEBUG [main] - Reader entry: <?xml version="1.0" encoding="UTF-8" ?> DEBUG [main] - Checking to see if class com.neuedu.mapper.UserMapperTest matches criteria [is assignable to Object] DEBUG [main] - Checking to see if class com.neuedu.mapper.UserMapper matches criteria [is assignable to Object] DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 209833425. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@c81cdd1] DEBUG [main] - ==> Preparing: SELECT * FROM T_USER WHERE username LIKE '%袁超%' DEBUG [main] - ==> Parameters: org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist ### The error may exist in com/neuedu/mapper/UserMapper.xml ### The error may involve com.neuedu.mapper.UserMapper.findUserByName-Inline ### The error occurred while setting parameters ### SQL: SELECT * FROM T_USER WHERE username LIKE '%袁超%' ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59) at com.sun.proxy.$Proxy3.findUserByName(Unknown Source) at com.neuedu.mapper.UserMapperTest.testFindUserByName(UserMapperTest.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.junit.runner.JUnitCore.run(JUnitCore.java:160) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.jdbc.Util.handleNewInstance(Util.java:400) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901) at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1193) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59) at com.sun.proxy.$Proxy5.execute(Unknown Source) at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63) at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) ... 29 more ``` # SqlMapConfig.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 加载属性文件 --> <properties resource="db.properties"> <!--properties中还可以配置一些属性名和属性值 --> <!-- <property name="jdbc.driver" value=""/> --> </properties> <!-- 全局配置参数,需要时再设置 --> <!-- <settings> </settings> --> <!-- 别名定义 --> <typeAliases> <!-- 针对单个别名定义 type:类型的路径 alias:别名 --> <!-- <typeAlias type="com.neuedu.mybatis.po.User" alias="user"/> --> <!-- 批量别名定义 指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以) --> <package name="com.neuedu.pojo"/> </typeAliases> <!-- 和spring整合后 environments配置将废除--> <environments default="development"> <environment id="development"> <!-- 使用jdbc事务管理,事务控制由mybatis--> <transactionManager type="JDBC" /> <!-- 数据库连接池,由mybatis管理--> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <!-- 加载 映射文件 --> <mappers> <mapper resource="sqlmap/User.xml"/> <!--通过resource方法一次加载一个映射文件 --> <!-- <mapper resource="sqlmap/User.xml"/> --> <!-- 通过mapper接口加载单个 映射文件 遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中 上边规范的前提是:使用的是mapper代理方法 --> <!-- <mapper class="com.neuedu.mapper.UserMapper"/> --> <!-- 批量加载mapper 指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载 遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中 上边规范的前提是:使用的是mapper代理方法 --> <package name="com.neuedu.mapper"/> </mappers> </configuration> ``` # User ``` public class User { //属性名和数据库表的字段对应 private int id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } } ``` 也不知道为什么,明明已经在UserMapper.xml里面把表名改了,但是报错信息里查找的还是T-user表 求大神指导!感恩! # 问题已解决 在maven文件里加上下面的代码 ``` <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*Mapper.xml</include> </includes> </resource> </resources> ```
java多线程高并发下的oracle数据库异常
代码的功能是生成一个随机的序列化的订单号,正常的情况下一个一个跑没问题,在进行压力测试的时候,多线程高并发下,oracle的create语句就会报错,说是 java.lang.RuntimeException: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sqlSQLException: ORA-00955: 名称已由现有对象使用 求大神看下。 代码如下: ``` package utils.spring; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import utils.Lang; import javax.sql.DataSource; import java.sql.*; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 序列发生器(可用于高并发、可回收等场景) * * @author lujijiang * */ @Component @ConfigurationProperties(prefix = "seqGenerator") final public class SequenceGenerator implements InitializingBean { interface Atom<T> { T atom(Connection connection) throws Exception; } public static <T> T atom(Connection connection, Atom<T> atom) throws Exception { connection.setAutoCommit(false); connection .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); try { T obj = atom.atom(connection); connection.commit(); return obj; } catch (Exception e) { connection.rollback(); throw e; } } static Map<String, String> createSqlMap = new ConcurrentHashMap<String, String>(); static { createSqlMap .put("h2", "CREATE TABLE %s (v$key BIGINT NOT NULL,v$key$ varchar(256),v$seq BIGINT NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("mysql", "CREATE TABLE %s (v$key BIGINT NOT NULL,v$key$ varchar(256),v$seq BIGINT NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("informix", "CREATE TABLE %s (v$key DECIMAL(16,0) NOT NULL,v$key$ varchar(256),v$seq DECIMAL(16,0) NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("oracle", "CREATE TABLE %s (v$key NUMBER(16,0) NOT NULL,v$key$ varchar2(256),v$seq NUMBER(16,0) NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); } static Map<String, String> insertSqlMap = new ConcurrentHashMap<String, String>(); static { insertSqlMap .put("h2", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select ifnull(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("mysql", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select ifnull(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("informix", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select nvl(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("oracle", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select nvl(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); } /** * 事务模版 */ TransactionTemplate transactionTemplate; /** * 是否使用新事务 */ boolean newTransaction = true; /** * JDBC模版 */ JdbcTemplate jdbcTemplate; /** * 尝试次数(默认10次) */ int tryTime = 10; /** * 数据库类型 */ String databaseType; /** * 表名 */ private String tableName; /** * 容量 */ private int capacity = 25; /** * 步进 */ private int step = 1; /** * 是否可回收序列号 */ protected boolean recyclable; @Autowired public void setTransactionManager( PlatformTransactionManager transactionManager) { if (transactionManager != null) { transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate .setIsolationLevel(TransactionTemplate.ISOLATION_READ_COMMITTED); transactionTemplate .setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED); } } public boolean isNewTransaction() { return newTransaction; } public void setNewTransaction(boolean newTransaction) { this.newTransaction = newTransaction; } public TransactionTemplate getTransactionTemplate() { return transactionTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Autowired public void setDataSource(DataSource dataSource) { if (jdbcTemplate == null) { jdbcTemplate = new JdbcTemplate(dataSource); } } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } public void setTryTime(int tryTime) { this.tryTime = tryTime; } public void setDatabaseType(String databaseType) { if (databaseType != null) { databaseType = databaseType.trim().toLowerCase(); this.databaseType = databaseType; } } public void setTableName(String tableName) { this.tableName = tableName == null ? null : tableName.trim(); } public void setCapacity(int capacity) { this.capacity = capacity; } public void setStep(int step) { this.step = step < 1 ? 1 : step; } public void setRecyclable(boolean recyclable) { this.recyclable = recyclable; } /** * 创建序列 * * @param name * @param length * @param start * @return */ public String generateSequence(String name, int length, long start) { final long key = generateKey(name); try { return generateSequence(key, length, start, name); } catch (Throwable t) { createSequenceTable();//错误就是定位在这里 int time = tryTime >= 0 ? tryTime : 10000; while (time-- > 0) { try { return generateSequence(key, length, start, name); } catch (Throwable e) { } } throw new RuntimeException("Generate sequence failure", t); } } private long generateKey(String name) { return 10000000000L + name.trim().hashCode(); } /** * 创建序列 * * @param key * @param length * @return */ public String generateSequence(String key, int length) { return generateSequence(key, length, 0); } /** * 创建序列 * * @param key * @return */ public String generateSequence(String key) { return generateSequence(key, 6); } private synchronized void createSequenceTable() { try { jdbcTemplate.execute(new ConnectionCallback<Integer>() { public Integer doInConnection(Connection connection) throws SQLException, DataAccessException { ResultSet rs = connection.getMetaData().getTables(null, null, tableName, null); try { while (rs.next()) { return 1; } } finally { rs.close(); } String createSql = String.format( createSqlMap.get(databaseType), tableName); Statement statement = connection.createStatement(); try { statement.execute(createSql);//错误就是定位在这里 } finally { statement.close(); } return 0; } }); } catch (Throwable t) { throw new RuntimeException(t); } } private String generateSequence(final long key, final int length, final long start, final String name) { if (newTransaction) { try { Connection connection = jdbcTemplate.getDataSource() .getConnection(); try { return atom(connection, new Atom<String>() { @Override public String atom(Connection connection) throws Exception { if (recyclable) { String no = getRecoveredSequence(connection, key, length); if (no != null) { return no; } } Statement statement = connection.createStatement(); try { String insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(connection, insertSql); String querySql = String .format("select max(v$seq) from %s where v$key=%d and v$state='1'", tableName, key); ResultSet rs = statement.executeQuery(querySql); try { while (rs.next()) { Long max = rs.getLong(1); if (max < start) {// 重新初始化 String deleteSql = String .format("delete from %s where v$key=%d and v$state='1'", tableName, key); execute(connection, deleteSql); insertSql = String.format( insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(connection, insertSql); return fillLeftZero(start, length); } if (capacity > 0 && max % capacity == 0) { String deleteSql = String .format("delete from %s where v$key=%d and v$seq<>%d and v$state='1'", tableName, key, max); execute(connection, deleteSql); } return fillLeftZero(max, length); } } finally { rs.close(); } } finally { statement.close(); } throw new IllegalStateException( SequenceGenerator.this.getClass() .getSimpleName() + "无法获取单号,不可能发生的异常"); } }); } finally { connection.close(); } } catch (Exception e) { throw Lang.unchecked(e); } } return getTransactionTemplate().execute( new TransactionCallback<String>() { public String doInTransaction(TransactionStatus ts) { try { if (recyclable) { String no = jdbcTemplate .execute(new ConnectionCallback<String>() { public String doInConnection( Connection connection) throws SQLException, DataAccessException { return getRecoveredSequence( connection, key, length); } }); if (no != null) { return no; } } String insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name .replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(insertSql); String querySql = String .format("select max(v$seq) from %s where v$key=%d and v$state='1'", tableName, key); Long max = jdbcTemplate.queryForObject(querySql, Long.class); if (max < start) {// 重新初始化 String deleteSql = String .format("delete from %s where v$key=%d and v$state='1'", tableName, key); execute(deleteSql); insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(insertSql); return fillLeftZero(start, length); } if (capacity > 0 && max % capacity == 0) { String deleteSql = String .format("delete from %s where v$key=%d and v$seq<>%d and v$state='1'", tableName, key, max); execute(deleteSql); } return fillLeftZero(max, length); } catch (Throwable t) { ts.isRollbackOnly(); throw new RuntimeException(t); } } }); } /** * 参数化执行SQL * * @param sql * @param args * @return */ protected int execute(String sql, final Object... args) { return jdbcTemplate.execute(sql, new PreparedStatementCallback<Integer>() { public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } return ps.executeUpdate(); } }); } /** * 参数化执行SQL * * @param sql * @param args * @return * @throws SQLException */ protected int execute(Connection conn, String sql, final Object... args) throws SQLException { PreparedStatement ps = conn.prepareStatement(sql); try { if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } return ps.executeUpdate(); } finally { ps.close(); } } protected String fillLeftZero(Long max, int length) { StringBuilder sb = new StringBuilder(); sb.append(max); if (sb.length() >= length) { return sb.substring(sb.length() - length); } else { for (int i = sb.length(); i < length; i++) { sb.insert(0, '0'); } } return sb.toString(); } /** * 获取已回收的序列 * * @param connection * @param key * @throws SQLException */ protected String getRecoveredSequence(Connection connection, long key, int length) throws SQLException { Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); try { String querySql = String .format("select v$key,v$seq,v$state from %s where v$key = %d and v$state<>'1' for update", tableName, key); statement.executeQuery(querySql); querySql = String .format("select v$key,v$seq,v$state from %s where v$key = %d and v$state<>'1' order by v$seq asc", tableName, key); ResultSet rs = statement.executeQuery(querySql); try { while (rs.next()) { try { Long min = rs.getLong(2); rs.updateString(3, "1"); rs.updateRow(); return fillLeftZero(min, length); } catch (Throwable ex) { } } } finally { rs.close(); } } finally { statement.close(); } return null; } /** * 回收序列号 * * @param name * @param sequence */ public void recoveredSequence(final String name, final String sequence) { final long key = generateKey(name); final long seq = Long.valueOf(sequence); if (newTransaction) { try { Connection connection = jdbcTemplate.getDataSource() .getConnection(); try { atom(connection, new Atom<Object>() { public Object atom(Connection connection) throws Exception { String updateSql = String .format("update %s set v$state='0' where v$key=%d and v$seq=%d", tableName, key, seq); int count = execute(connection, updateSql); if (count == 0) { String insertSql = String .format("insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',%d,'0')", tableName, key, name.replace("'", "''"), seq); execute(connection, insertSql); } return null; } }); connection.commit(); } finally { connection.close(); } } catch (Exception e) { throw Lang.unchecked(e); } } else { transactionTemplate.execute(new TransactionCallback<Integer>() { public Integer doInTransaction(TransactionStatus status) { try { String updateSql = String .format("update %s set v$state='0' where v$key=%d and v$seq=%d", tableName, key, seq); int count = execute(updateSql); if (count == 0) { String insertSql = String .format("insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',%d,'0')", tableName, key, name.replace("'", "''"), seq); execute(insertSql); } return null; } catch (Throwable t) { status.isRollbackOnly(); throw new RuntimeException(t); } } }); } } public void afterPropertiesSet() throws Exception { if (this.databaseType == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "databaseType")); } if (databaseType != null) { if (!createSqlMap.containsKey(databaseType)) { throw new IllegalStateException(String.format( "Unsupported database type:%s", databaseType)); } } if (this.jdbcTemplate == null) { throw new IllegalArgumentException(String.format( "Property '%s' or '%s' is required", "dataSource", "jdbcTemplate")); } if (this.tableName == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "tableName")); } if (!tableName.matches("[a-zA-Z_][a-zA-Z0-9_]*") || tableName.length() > 16) { throw new IllegalStateException(String.format( "Illegal tableName:%s", tableName)); } if (!this.newTransaction) { if (this.transactionTemplate == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "transactionManager")); } } } } ``` java.lang.RuntimeException: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at utils.spring.SequenceGenerator.createSequenceTable(SequenceGenerator.java:272) at utils.spring.SequenceGenerator.generateSequence(SequenceGenerator.java:202) at utils.spring.SequenceGenerator.generateSequence(SequenceGenerator.java:227) at cart.service.service.OrderService.generateOrderNo(OrderService.java:806) at cart.service.service.OrderService.saveVirtualGoodsToOrder(OrderService.java:220) at cart.service.service.OrderService$$FastClassBySpringCGLIB$$19f99be7.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) at cart.service.service.OrderService$$EnhancerBySpringCGLIB$$feb8eef.saveVirtualGoodsToOrder(<generated>) at cart.service.apiImpl.OrderMainApiImpl.saveVirtualGoodsToOrder(OrderMainApiImpl.java:223) at cart.service.apiImpl.OrderMainApiImpl$$FastClassBySpringCGLIB$$fa3518e.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651) at cart.service.apiImpl.OrderMainApiImpl$$EnhancerBySpringCGLIB$$497f044.saveVirtualGoodsToOrder(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.weibo.api.motan.rpc.DefaultProvider.invoke(DefaultProvider.java:57) at com.weibo.api.motan.rpc.AbstractProvider.call(AbstractProvider.java:47) at com.weibo.api.motan.filter.AccessLogFilter.filter(AccessLogFilter.java:56) at com.weibo.api.motan.protocol.support.ProtocolFilterDecorator$2.call(ProtocolFilterDecorator.java:150) at utils.rpc.motan.filter.OpenEntityManagerInMotanFilter.filter(OpenEntityManagerInMotanFilter.java:171) at com.weibo.api.motan.protocol.support.ProtocolFilterDecorator$2.call(ProtocolFilterDecorator.java:150) at com.weibo.api.motan.transport.ProviderMessageRouter.call(ProviderMessageRouter.java:96) at com.weibo.api.motan.transport.ProviderProtectedMessageRouter.call(ProviderProtectedMessageRouter.java:79) at com.weibo.api.motan.transport.ProviderMessageRouter.handle(ProviderMessageRouter.java:91) at com.weibo.api.motan.transport.support.DefaultRpcHeartbeatFactory$HeartMessageHandleWrapper.handle(DefaultRpcHeartbeatFactory.java:82) at com.weibo.api.motan.transport.netty.NettyChannelHandler.processRequest(NettyChannelHandler.java:139) at com.weibo.api.motan.transport.netty.NettyChannelHandler.access$000(NettyChannelHandler.java:47) at com.weibo.api.motan.transport.netty.NettyChannelHandler$1.run(NettyChannelHandler.java:116) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:360) at utils.spring.SequenceGenerator.createSequenceTable(SequenceGenerator.java:247) ... 39 more Caused by: java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288) at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:210) at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:961) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1190) at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1726) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1696) at utils.spring.SequenceGenerator$1.doInConnection(SequenceGenerator.java:264) at utils.spring.SequenceGenerator$1.doInConnection(SequenceGenerator.java:247) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:353) ... 40 more
mysql的JDBC封装类如何释放资源?
在这个类中返回出一个Resultset结果,然后在另一个类中循环出来,有什么办法可以在这个类中直接释放资源?如果直接在后面加finally{...}会报错,初学求解 public ResultSet SQL_ExecuteQuery(String sql,Object [] p) { Connection con=openConnection();//打开数据库 PreparedStatement pst=null;//定义一个 执行对象 ResultSet rst=null; try { pst=con.prepareStatement(sql);//初始化执行对象 //循环设置参数 if(p!=null && p.length>0) { for (int i = 0; i < p.length; i++) { pst.setObject((i+1), p[i]);//设置参数 } } rst=pst.executeQuery(); //最后执行命令 并返回结果 return rst;//执行命令 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
JDBC 一个链接执行两条语句出错
我想在一个参数中两次执行sql语句 得到结果凭借成json数组 但是报错 无法操作 请高手来看一下 函数代码: ``` public JSONArray check(work work) throws Exception { try { String sql = "select e_name,w_date,w_time,w_score,w_title,w_content,achieve1,achieve2,achieve3,achieve4 FROM WORK where w_number=?"; int k=work.getw_number(); pstmt = conn.prepareStatement(sql);// 实例化操作 pstmt.setInt(1, work.getw_number()); ResultSet rSet = pstmt.executeQuery();// 取得结果 JSONArray array = new JSONArray();//定义jsonarray ResultSetMetaData metaData = rSet.getMetaData(); int columnCount= metaData.getColumnCount(); while (rSet.next()){ JSONObject jsonObj = new JSONObject(); //遍历ResultSetMetaData数据每一列 for(int i = 1; i <= columnCount;i++) { String columnName = metaData.getColumnLabel(i); String value =rSet.getString(columnName); jsonObj.put(columnName, value); } array.add(jsonObj); } System.out.println(array.toString()+"checkhoutai1"); String sql2 = "select r_number,r_content,r_employee,r_time FROM REVIEW where w_number=? "; pstmt2 = conn.prepareStatement(sql2);// 实例化操作 pstmt2.setInt(1, k); ResultSet rSet2 = pstmt2.executeQuery();// 取得结果 ResultSetMetaData metaData2 = rSet2.getMetaData(); int columnCount2= metaData2.getColumnCount(); while (rSet2.next()) { JSONObject jsonObj = new JSONObject(); //遍历ResultSetMetaData数据每一列 for(int i = 1; i <= columnCount2;i++) { String columnName = metaData2.getColumnLabel(i); String value =rSet2.getString(columnName); jsonObj.put(columnName, value); } array.add(jsonObj); } System.out.println(array.toString()+"checkhoutai"); return array; } catch (Exception e) { throw e; } finally { // 关闭操作 if (pstmt2 != null) { try { pstmt2.close(); } catch (Exception e) { throw e; } } } } ``` 数据库为mysql 连接数据库的参数单另做在一个.java文件中 连接数据库: ``` /** *功能 定义数据库操作类 */ package com.zhisland.db; import java.sql.Connection; import java.sql.DriverManager; public class DatabaseConnection { //定义数据库驱动程序 private static final String DBDRIVER="com.mysql.jdbc.Driver"; //数据库连接地址 private static final String DBURL="jdbc:mysql://XXXXXX/zhisland";//company表示数据库 private static final String DBUSER="root"; private static final String DBPASS="XXXXXX"; private Connection connection=null; public DatabaseConnection() throws Exception{ try{ //数据库操作可能出现异常 Class.forName(DBDRIVER); connection=DriverManager.getConnection(DBURL,DBUSER,DBPASS); }catch(Exception exception ){ throw exception; } finally { } } public Connection getConnection(){ return connection; } public void close() throws Exception{ if(connection!=null){ try { connection.close(); } catch (Exception e) { throw e; } } } } ``` 报错信息: ``` java.sql.SQLException: Column 'r_number' not found. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919) at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1166) at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5732) at com.zhisland.dao.DAOImpI.check(DAOImpI.java:324) at com.zhisland.dao.proxy.DAOProxy.check(DAOProxy.java:98) at com.zhisland.servlet.checkwork.doPost(checkwork.java:52) at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1368) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) ```
有没有大神能指点一下哪里错了。。。。
package Frame; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; import javax.swing.*; import db.DButil; public class login extends JFrame implements ActionListener{ private JPanel jp=new JPanel(); //创建标签数组 private JLabel[] jlArray={new JLabel("用户名"), new JLabel("密 码"),new JLabel("")}; private JButton jb1; private JButton jb2; private JButton jb3; private JTextField jtf=new JTextField(); private JPasswordField jpf=new JPasswordField(); //布局构造实现方法 public login(){ Icon icon1=new ImageIcon("login.jpg"); Icon icon2=new ImageIcon("reset.jpg"); Icon icon3=new ImageIcon("zhuce.jpg"); JPanel jp=new JPanel(){ protected void paintComponent(Graphics g) { ImageIcon icon = new ImageIcon("bg.jpg"); Image img = icon.getImage(); g.drawImage(img, 0, 0, icon.getIconWidth(), icon.getIconHeight(), icon.getImageObserver()); }}; jp.setLayout(null); jb1=new JButton(icon1); jb2=new JButton(icon3); jb3=new JButton(icon2); jlArray[0].setBounds(70,120,90,32); jb1.setBounds(365,110,130,60); jb2.setBounds(365,170,130,60); jlArray[1].setBounds(70,170,90,32); //将标签与按钮添加到JPanel容器中 jp.add(jlArray[0]); jp.add(jlArray[1]); jp.add(jb1); jp.add(jb2); jb1.addActionListener(this); jb2.addActionListener(this);//为按钮注册动作事件监听器 //添加修改密码的按钮 jb3.setBounds(365,230,130,60); jp.add(jb3); jp.add(jtf); jtf.setBounds(140,120,180,30);//设置文本框位置 jp.add(jpf); jpf.setBounds(140,170,180,30);//设置密码框位置 jpf.setEchoChar('*'); //密码显示字符形式 jpf.addActionListener(this); //为密码框注册动作事件监听器 this.setVisible(true);//设置窗体的可见性 jpf.addActionListener(this); //为密码框注册动作事件监听器 //设置用于显示登陆状态的标签大小位置,并将其添加进JPanel容器 jlArray[2].setBounds(70,220,300,30); jp.add(jlArray[2]); this.setTitle("登陆");//设置窗体标题 this.setBounds(450,200,500,318);//设置窗体的大小 this.setResizable(false);//设置窗体不让用户调整大小 this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setVisible(true);//设置窗体的可见性 this.add(jp);//将窗体添加到面板中 jp.setBackground(Color.blue); } public static void main(String[] args) { new login();//创建登陆窗体 } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //得到用户名与密码 String user=jtf.getText().trim(); String pwd=String.valueOf(jpf.getPassword());//返回密码的字符串表示方式 String sql=""; if(e.getSource()==jtf){//事件源为文本框,切换焦点到密码框 jpf.requestFocus(); } else if(e.getSource()==jb1||e.getSource()==jpf){ //判断用户名和密码是否匹配 查询数据库 if(DButil.check(user, pwd)){ //登陆成功 MainFrame mf=new MainFrame(jtf.getText());//主窗体 this.dispose(); } else{ //登陆失败 jlArray[2].setText("对不起,非法的用户名和密码"); this.clear(); } } else if(e.getSource()==jb2) {//事件源为注册按钮 if(user.equals("")||pwd.equals("")) {//如果注册的用户名为空或者密码为空 jlArray[2].setText("用户名和密码都不得为空!!!"); this.clear();//清空输入文本框 } else { sql="select uid from user where uid='"+user+"'"; if(DButil.isExist(sql)) {//用户名已经存在 jlArray[2].setText("对不起,用户名已存在!!!"); this.clear();//清空输入文本框 } else { sql="insert into user values('"+user+"','"+pwd+"')"; if(DButil.update(sql)>0) {//注册成功 jlArray[2].setText("恭喜您!!!注册成功,请登陆"); } } } } else if(e.getSource()==jb3)//修改密码的监听 { //判断是否已经输入用户名和密码 if(user.equals("")||pwd.equals("")) { jlArray[2].setText("修改密码先输入正确的用户名和密码!!!"); this.clear();//清空输入文本框 } //判断是否输入了正确的用户名和密码 else if(DButil.check(user,pwd)) { //正确的用户名和密码 String password=JOptionPane.showInputDialog(this,"修改密码:","请输入新密码", JOptionPane.PLAIN_MESSAGE); //得到新的密码为空 if(password==null||password.equals("")) { JOptionPane.showMessageDialog(this,"密码不得为空!!!","错误", JOptionPane.WARNING_MESSAGE); } else {//密码不为空 sql="update user set pwd='"+password+"' where uid='"+user+"'";//更新密码的SQL if(DButil.update(sql)>0) {//密码修改成功 this.clear();//清空输入文本框 jlArray[2].setText("恭喜您!!!密码修改成功,请用新密码登陆"); } } } else { JOptionPane.showMessageDialog(this,"用户名或者密码错误!!!","错误", JOptionPane.WARNING_MESSAGE); this.clear();//清空输入文本框 } } } package Frame; import javax.swing.*; import javax.swing.table.DefaultTableModel; import db.DButil; import java.awt.*; import java.awt.event.*; import java.sql.*; import java.io.*; import java.util.*; public class MainFrame extends JFrame implements ActionListener,ItemListener { private String uname=null;//当前用户的名字 private boolean isInsert=false;//是否为添加默认为否 private JPanel topjp=new JPanel();//界面上半部分的JPanel容器 private JButton jba=new JButton("模糊查询"); private JButton jbs=new JButton("查找"); private JTextField jtfs=new JTextField();//按给出信息查找联系人信息 private JRadioButton jrbxm=new JRadioButton("按姓名查找",true); private JRadioButton jrbbh=new JRadioButton("按学号查找",false); private ButtonGroup bg=new ButtonGroup();//单选按钮组 private JPanel jpbr=new JPanel();//单选按钮面板 private JPanel jpyInfo=new JPanel();//右侧显示个人信息的面板 private JTextArea jta=new JTextArea(); // 模糊查询得到的信息文本区 private JLabel[] jlInfo={new JLabel("学号:"),new JLabel("姓名:"), new JLabel("性别:"),new JLabel("出生日期:"), new JLabel("电话号码:"),new JLabel("QQ:"), new JLabel("Email:"),new JLabel("地址:"), new JLabel("添加相片")}; private JButton[] jbInfo={new JButton("编辑"),new JButton("保存"), new JButton("浏览"), new JButton("上传"),}; private JLabel jlPhoto=new JLabel();//显示图像的JLabel控件 private JTextField[] jtfInfo=new JTextField[10]; private JTextField jtfPhoto=new JTextField();//添加照片到相册的路径 private JFileChooser jfcPic=new JFileChooser();//上传图像的文件选择器 private DefaultTableModel tableModel; private JTable table; //性别部分 private JRadioButton jrbMale=new JRadioButton("男",true); private JRadioButton jrbFemale=new JRadioButton("女"); private ButtonGroup bgGender=new ButtonGroup(); private JPanel jpGender=new JPanel();//单选按钮面板 private JLabel jlDetail=new JLabel();//右侧显示一幅图片的标签 private JSplitPane jspOuter=//上下分割的JSplitPane new JSplitPane(JSplitPane.VERTICAL_SPLIT,true); //系统托盘部分 private PopupMenu popup=new PopupMenu(); private SystemTray tray;//定义SystemTray成员变量 private TrayIcon trayIcon;//定义TrayIcon成员变量 private MenuItem exit=new MenuItem("退出程序");//定义菜单 public void initJps() {//界面上半部分的初始化 topjp.setLayout(null);//设置topjp布局管理器为null //设置按钮大小并添加到JPanel面板里 jba.setBounds(5,10,120,26); jba.addActionListener(this);//为模糊查询按钮注册事件监听器 topjp.add(jba); jbs.setBounds(130,10,80,26); jbs.addActionListener(this);//为查找按钮注册事件监听器 topjp.add(jbs);//添加按钮到topjp面板里 //设置jtfs文本框大小并添加到jps面板里 jtfs.setBounds(215,10,120,26); jtfs.addActionListener(this);//为文本框注册事件监听器 topjp.add(jtfs); //设置单选按钮大小和位置并添加到jpbr面板里同时添加到bg单选按钮组里 jrbxm.setBounds(5,3,50,26); jrbxm.addItemListener(this);//为单选按钮注册ItemEvent事件监听器 bg.add(jrbxm); jpbr.add(jrbxm); jrbbh.setBounds(60,3,50,26); jrbbh.addItemListener(this); bg.add(jrbbh); jpbr.add(jrbbh); jpbr.setBounds(360,10,200,26); topjp.add(jpbr); } public void initInfo() {//初始化信息界面 jpyInfo.setLayout(null);//设置布局管理器为空 jpyInfo.setBounds(50,50,380,360);//设置信息面板的大小和位置 jlPhoto.setBounds(220,10,150,170);//设置联系人图像JLabel的大小和位置 jlPhoto.setBorder(BorderFactory.createLineBorder(Color.BLACK));//将JLbel的边框线显现出来 jpyInfo.add(jlPhoto);//将显示联系人照片的JLabel添加到信息面板 tableModel=new DefaultTableModel(); Vector vector1 = new Vector(); DButil db = new DButil(); vector1.add("学号"); vector1.add("姓名"); vector1.add("性别"); vector1.add("出生日期"); vector1.add("电话号码"); vector1.add("QQ"); vector1.add("Email"); vector1.add("地址"); vector1.add("照片路径"); tableModel.setDataVector(null, vector1); System.out.print(123); table=new JTable(tableModel); //table.addMouseListener((MouseListener) this); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JScrollPane js=new JScrollPane(table); //添加相片部分的控件 jtfPhoto.setBounds(80,250,200,26);//设置得到照片路径的文本框的大小和位置 jpyInfo.add(jtfPhoto);//将得到照片路径的文本框添加到信息面板 jbInfo[2].setBounds(285,250,80,26); jbInfo[2].addActionListener(this);//为添加照片的浏览按钮注册事件监听器 jpyInfo.add(jbInfo[2]); //上传按钮 jbInfo[3].setBounds(380,250,80,26); jbInfo[3].addActionListener(this);//为添加照片的浏览按钮注册事件监听器 jpyInfo.add(jbInfo[3]); for(int i=0;i<9;i++)//添加JLabel,并设置大小和位置 { jlInfo[i].setBounds(20,10+i*30,60,26); jpyInfo.add(jlInfo[i]); } for(int i=0;i<10;i++) {//初始化一些文本框 jtfInfo[i]=new JTextField(); } //学号 jtfInfo[0].setBounds(80,10,135,26); jpyInfo.add(jtfInfo[0]); //姓名 jtfInfo[1].setBounds(80,40,135,26); jpyInfo.add(jtfInfo[1]); //出生日期 jtfInfo[3].setBounds(80,100,135,26); jpyInfo.add(jtfInfo[3]); //电话号码 jtfInfo[4].setBounds(80,130,135,26); jpyInfo.add(jtfInfo[4]); //QQ jtfInfo[5].setBounds(80,160,135,26); jpyInfo.add(jtfInfo[5]); //Email jtfInfo[6].setBounds(80,190,135,26); jpyInfo.add(jtfInfo[6]); //地址文本框的添加 jtfInfo[7].setBounds(80,220,285,26); jpyInfo.add(jtfInfo[7]); //模糊查询信息文本区的添加 js.setBounds(0,350,600,100); jpyInfo.add(js); //编辑、保存按钮 jbInfo[0].setBounds(160,300,80,26); jbInfo[0].addActionListener(this); jpyInfo.add(jbInfo[0]); jbInfo[1].setBounds(260,300,80,26); jbInfo[1].addActionListener(this); jpyInfo.add(jbInfo[1]); //性别部分 jrbMale.setBounds(5,3,50,26); jrbMale.addItemListener(this); //为单选按钮注册ItemEvent事件监听器 bgGender.add(jrbMale); jpGender.add(jrbMale); jrbFemale.setBounds(60,3,50,26); jrbFemale.addItemListener(this); //为单选按钮注册ItemEvent事件监听器 bgGender.add(jrbFemale); jpGender.add(jrbFemale); jpGender.setBounds(60,70,125,26); jpyInfo.add(jpGender); } public void clearInfo()//清空信息面板 { for(int i=0;i<10;i++) { jtfInfo[i].setText("");//清空文本框 } jlPhoto.setIcon(null);//清空图像 } public void setjtaArea(String information){ if(information.isEmpty()){ JOptionPane.showMessageDialog(this,"所查用户不存在!!!","错误", JOptionPane.WARNING_MESSAGE); } else { jta.setText(information); } } public void setInfo(Vector<String> pInfo)//将信息向量设置到信息面板中 {//将信息向量按规则填到信息面板里 this.clearInfo(); if(pInfo.size()==0) { JOptionPane.showMessageDialog(this,"所查用户不存在!!!","错误", JOptionPane.WARNING_MESSAGE); } else { for(int i=0;i<2;i++) {//显示联系人编号和姓名 jtfInfo[i].setText(pInfo.get(i)); } if(pInfo.get(2).equals("男")) {//显示性别 jrbMale.setSelected(true); } else {//显示性别 jrbFemale.setSelected(true); } for(int i=3;i<9;i++) {//显示出生日期、电话号码和QQ jtfInfo[i].setText(pInfo.get(i)); } } } public Vector<String> getInfo()//从信息面板得到用户输入的信息 { Vector<String> pInfo=new Vector<String>(); pInfo.add(jtfInfo[0].getText().trim());//添加pid pInfo.add(jtfInfo[1].getText().trim());//添加pname String gender=jrbMale.isSelected()?"男":"女"; pInfo.add(gender);//添加性别 pInfo.add(jtfInfo[3].getText().trim());//出生日期 pInfo.add(jtfInfo[4].getText().trim());//电话号码 pInfo.add(jtfInfo[5].getText().trim());//QQ pInfo.add(jtfInfo[6].getText().trim());//Email pInfo.add(jtfInfo[7].getText().trim());//地址 String photoPath=jtfPhoto.getText().trim();//得到照片路径 pInfo.add(photoPath);//照片路径 return pInfo; } public void monitorSaveButton() //监听保存按钮的方法 { String sql=""; String pid=jtfInfo[0].getText().trim();//得到联系人的编号 String pname=jtfInfo[1].getText().trim();//得到联系人的姓名 String gender=jrbMale.isSelected()?"男":"女"; String s1=jtfInfo[3].getText().trim(); String s2=jtfInfo[4].getText().trim(); String s3=jtfInfo[5].getText().trim(); String s4=jtfInfo[6].getText().trim(); String s5=jtfInfo[7].getText().trim(); String s6=jtfPhoto.getText().trim(); String sqla="select * from contacts where pid='"+pid+"'";//判断此编号是否存在的SQL String sqlb="select * from contacts where pname='"+pname+"'";//判断此姓名是否存在的SQL boolean isIdExist=DButil.isExist(sqla);//得到编号是否存在 boolean isNameExist=DButil.isExist(sqlb);//得到姓名是否存在 if(!(pid.equals(" ")||pname.equals(" "))) { if(isIdExist||isNameExist){ JOptionPane.showMessageDialog(this,"联系人已存在"+ " , 添加联系人失败","错误",JOptionPane.WARNING_MESSAGE); } else { sql="insert into contacts values (?,?,?,?,?,?,?,?,?,?)"; String[] paras={pid,pname,gender,s1,s2,s3,s4,s5,s6,null}; if(DButil.update(sql,paras)>0){ JOptionPane.showMessageDialog(this,"联系人保存成功","提示", JOptionPane.INFORMATION_MESSAGE); } } } } public void setEditable(boolean Editable)//设置信息窗口是否可编辑 { jrbFemale.setEnabled(Editable);//设置性别是否可编辑 jrbMale.setEnabled(Editable);//设置性别是否可编辑 for(int i=0;i<8;i++) { jtfInfo[i].setEditable(Editable);//设置文本框是否可编辑 } } public void monitorSearchButton()//监听查找按钮的方法 { String name=jtfs.getText().trim(); String sql="";//声明查找字符串 if(name.equals("")) { JOptionPane.showMessageDialog(this,"查找条件不能为空!!!", "错误", JOptionPane.WARNING_MESSAGE); } else { if(jrbxm.isSelected()==true) {//按姓名查找 sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where pname='"+name+"'"; this.setInfo(DButil.getPerInfo(sql));//设置信息面板为该联系人的信息 } else {//按编号查找 sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where pid='"+name+"'"; this.setInfo(DButil.getPerInfo(sql));//设置信息面板为该联系人的信息 } } this.setEditable(false);//设置面板不可编辑 } public void monitorRandomSearchButton(String information){ //监听模糊查询按钮 String adress=jba.getText().trim(); String sql="";//声明查找字符串 if(adress.equals("")) { JOptionPane.showMessageDialog(this,"查找条件不能为空!!!", "错误", JOptionPane.WARNING_MESSAGE); } else{ sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where padress like '%天河区%'"; } } public MainFrame(String uname) { //主窗体构造器 this.uname=uname;//设置用户名 this.initJps();//界面上半部分的搭建 this.initInfo(); jspOuter.setDividerLocation(46);//设置分割窗体JSplitPane的位置 jspOuter.setTopComponent(topjp);//设置窗体上半部分的控件 jspOuter.setBottomComponent(jpyInfo);//设置下半部分的控件 //设置窗体关闭按钮执行的动作 this.add(jspOuter); this.addWindowListener( new WindowAdapter() { @SuppressWarnings("deprecation") public void WindowClosing(WindowEvent e) { //将窗体隐藏 MainFrame.this.hide(); } } ); //设置主窗体的图标、标题、大小以及可见性 this.setResizable(false);//设置窗体不让调整大小 this.setTitle(uname+"的通讯录"); this.setBounds(420,80,618,550); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource()==jbInfo[1]) {//保存按钮的监听 this.monitorSaveButton(); } else if(e.getSource()==jba) {//模糊查询按钮的监听 DButil db = new DButil(); Vector vector1 = new Vector(); vector1.add("学号"); vector1.add("姓名"); vector1.add("性别"); vector1.add("出生日期"); vector1.add("电话号码"); vector1.add("QQ"); vector1.add("Email"); vector1.add("地址"); vector1.add("照片路径"); String ad = jtfs.getText().trim(); tableModel.setDataVector(db.getData(ad),vector1); } else if(e.getSource()==jbInfo[2]) {//打开图像文件路径 jfcPic.showOpenDialog(this); if(jfcPic.getSelectedFile()!=null) { jtfPhoto.setText(""+jfcPic.getSelectedFile()); } } else if(e.getSource()==jbInfo[0]) {//编辑按钮的监听 this.setEditable(true);//设置信息面板可编辑 } else if(e.getSource()==jbs||e.getSource()==jtfs) {//查找,按按钮或者在文本框里敲回车 this.monitorSearchButton(); } } public void itemStateChanged(ItemEvent e) { } public static void main(String[] args){ } } package db; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.Vector; public class DButil { private static String jdbcName="org.gjt.mm.mysql.Driver";//声明驱动类字符串 //声明数据库连接字符串 private static String dbUrl="jdbc:mysql://127.0.0.1:3306/maillist"; private static String dbUserName="root"; private static String dbPassword="admin"; private static Connection con=null;//声明数据库连接对象引用 private static Statement stat=null;//声明语句对象引用 private static PreparedStatement pstmt=null; private static ResultSet rs=null;//声明结果集对象引用 private static PreparedStatement psInsert=null;//声明预编译语句对象引用 public static Connection getConnection()//得到数据库连接的方法 { System.out.println("连接中.."); try { Class.forName(jdbcName);//加载驱动类 con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);//得到连接 System.out.println("成功连接"); } catch(Exception e){e.printStackTrace();} return con;//返回连接 } public static boolean check(String user,String pwd)//登陆验证 { boolean flag=false; try { con=DButil.getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery("select pwd from user where uid='"+user+"'"); rs.next(); String spwd=rs.getString(1);//得到密码 if(spwd.equals(pwd)) { flag=true;//密码匹配,登陆成功 } } catch(Exception e) { flag=false;//有任何异常发生,登陆失败 } finally{DButil.closeCon();}//关闭数据库连接 return flag; } //某条记录是否存在 public static boolean isExist(String sql) { boolean flag=false;//设置返回值 try { con=DButil.getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery(sql);//执行查询 if(rs.next()) { flag=true;//存在,设置返回值为true } } catch(Exception e) { e.printStackTrace(); flag=false;//发生任何异常,置返回结果为false } finally{DButil.closeCon();}//关闭数据库连接 return flag;//返回结果 } public static int update(String sql,String[] paras)//更新数据库 { int count=0;//声明返回值 try { con=DButil.getConnection(); pstmt=con.prepareStatement(sql); for(int i=0; i<paras.length;i++){ pstmt.setString(i+1, paras[i]); } count=pstmt.executeUpdate(); } catch(Exception e) { e.printStackTrace(); count=-1;//更新失败返回值为-1 } finally{DButil.closeCon();}//关闭数据库连接 return count;//返回结果 } public static int update(String sql)//更新数据库 { int count=0;//声明返回值 try { con=DButil.getConnection(); stat=con.createStatement(); count=stat.executeUpdate(sql);//执行更新 } catch(Exception e) { e.printStackTrace(); count=-1;//更新失败返回值为-1 } finally{DButil.closeCon();}//关闭数据库连接 return count;//返回结果 } //====================添加联系人================================= public static String insertPerson(String uid,Vector<String> pInfo) { String isPathNull="isNotNull";//传过来的图像是不是合法,默认不为空 try{ con=getConnection();//得到数据库连接 if(pInfo.get(8).equals("")||pInfo.get(8)==null) {//照片路径为空,则不插入图像 psInsert=con.prepareStatement("insert into contacts(pid,pname,pgender,pbirthday,pnumber,"+ "pQQ,pemail,padress,uid)"+ "values(?,?,?,?,?,?,?,?,?)"); } else {//照片路径不为空,则插入图像 psInsert=con.prepareStatement("insert into contacts(pid,pname,pgender,pbirthday,pnumber,"+ "pQQ,pemail,padress,pphoto,uid)"+ "values(?,?,?,?,?,?,?,?,?,?,?)" ); File f=new File(pInfo.get(8));//获取选取的图片文件 byte[] b=new byte[(int)f.length()];//创建存储图片数据的数组 FileInputStream fin=new FileInputStream(f); fin.read(b);fin.close();//读取文件存于byte数组中并关闭输入流 psInsert.setBytes(11,b);//设置pphoto参数的数据 } for(int i=0;i<8;i++) {//设置公共信息 psInsert.setString(i+1,pInfo.get(i)); } psInsert.setString(10,uid);//所属用户 psInsert.execute();psInsert.close();//执行更新并关闭语句 } catch(FileNotFoundException fnfe){isPathNull="isNull";}//图片路径不对 catch(Exception e){e.printStackTrace();} finally{DButil.closeCon();}//关闭数据库连接 return isPathNull; } public static String updatePerson(String uid,Vector<String> pInfo){ String isPathNull="isNotNull";//传过来的path是不是合法 try{ con=getConnection(); if(pInfo.get(9).equals("")||pInfo.get(9)==null) {//更新时候,如果照片路径为空,则不更新图像 psInsert=con.prepareStatement("update contacts set pname=?,pgender=?,birthday=?,pnumber=?,"+ "pQQ=?,pemail=?,padress=?,pphoto=?,uid=? where pid='"+pInfo.get(0).trim()+"'"); } else {//如果照片路径不为空,则更新图像 psInsert=con.prepareStatement("update contacts set pname=?,pgender=?,page=?,pnumber=?,"+ "pemail=?,pgroup=?,ppostalcode=?,padress=?,uid=?,pphoto=? where pid='"+pInfo.get(0).trim()+"'"); File f=new File(pInfo.get(9));//获取选取的图片文件 byte[] b=new byte[(int)f.length()];//创建存储图片数据的数组 FileInputStream fin=new FileInputStream(f); fin.read(b);fin.close();//读取文件存于byte数组中并关闭输入流 psInsert.setBytes(10,b); } for(int i=1;i<8;i++){//设置公共的信息部分 psInsert.setString(i,pInfo.get(i)); } psInsert.setString(9,uid);//所属用户 psInsert.execute();psInsert.close();//执行更新并关闭语句 } catch(FileNotFoundException fnfe){isPathNull="isNull";}//路径不合法 catch(Exception e){e.printStackTrace();} finally{DButil.closeCon();}//关闭连接 return isPathNull; } public Vector getData(String ad){ Vector vector=new Vector(); try { //陈述对象 con=getConnection();//得到数据库连接 stat=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);//创建语句对象 rs=stat.executeQuery("select * from contacts where padress LIKE '%"+ad+"%'"); ResultSetMetaData rm=rs.getMetaData(); //循环打印出数据库表中数据 int n=rm.getColumnCount(); while(rs.next()){ Vector ve=new Vector(); for(int i=1;i<n+1;i++){ String s=rs.getString(i); ve.add(s); } vector.add(ve);//Vector对象接收表中数据 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{if(rs!=null){ try { rs.close();//关闭结果集 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(stat!=null){ try { stat.close();//关闭陈述对象 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(con!=null){ try { con.close();//关闭连接 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return vector; } public static Vector<String> getPerInfo(String sql)//得到联系人信息 { Vector<String> pInfo=new Vector<String>(); try { con=getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery(sql);//执行查询 while(rs.next()) { for(int i=1;i<10;i++) { System.out.println(rs.getString(i)); pInfo.add(rs.getString(i));//将联系人信息添加到返回向量 } } } catch(Exception e) { e.printStackTrace(); } finally{DButil.closeCon();}//关闭数据库连接 return pInfo;//返回信息集合 } public static void closeCon()//关闭数据库连接的方法 { try { if(rs!=null){rs.close(); rs=null;}//如果结果集不为空关闭结果集并赋值null if(stat!=null){stat.close(); stat=null;}//如果语句对象不为空关闭语句对象并赋值null if(con!=null){con.close(); con=null;}//如果连接不为空关闭连接并赋值null } catch(Exception e){e.printStackTrace();} } public static void main(String[] args){ DButil DB=new DButil(); System.out.println(DB.getConnection()); } } }
自己封装了一个线程池,求大神帮忙看下有没有安全方面的问题
自己封装的一个jdbc,给jdbc增加了一个连接池,但是不知道有没有问题,所以让大神们帮忙看下,我写的这个线程池有没有问题 ``` package tool; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Jdbc { //连接池中的连接 private Connection conn; private ResultSet rs; private ResultSetMetaData md; private PreparedStatement ps; private JSONArray list; private JSONObject map; private String classpath = getClass().getResource("/").getPath(); private String path = classpath + "jdbc.properties"; private BlockingQueue<Connection> connections = new LinkedBlockingQueue<>(); public Jdbc(){} /** * 初始化Jdbc连接池 * @param poolSize 连接池大小 * @throws IOException * @throws ClassNotFoundException * @throws SQLException * @throws InterruptedException */ public void initJdbcPool() throws IOException, ClassNotFoundException, SQLException, InterruptedException { FileInputStream fis = new FileInputStream(path); Properties prop = new Properties(); prop.load(fis); String url = prop.getProperty("db.url"); String user = prop.getProperty("db.user"); String psw = prop.getProperty("db.password"); Integer connectionNum = Integer.parseInt(prop.getProperty("connectionNum")); Class.forName(prop.getProperty("driverClass")); for (int i = 0; i < connectionNum; i++) { //获取数据库的连接 Connection dbConn = DriverManager.getConnection(url, user, psw); //System.out.println(dbConn); connections.put(dbConn); } } public void destroyJdbcPool() { connections.clear(); } /** * 从连接池中获取链接 * @return * @throws InterruptedException */ private Connection getConnection() throws InterruptedException { return connections.take(); } /** * 把连接放回到连接池中,并关闭声明对象和结果集对象 * @param connection 连接 * @param ps 声明对象 * @param rs 结果集对象 * @throws SQLException * @throws InterruptedException */ private void backConnection(Connection connection,PreparedStatement ps,ResultSet rs) throws SQLException, InterruptedException { if(ps!=null) ps.close(); if(rs!=null) rs.close(); connections.put(connection); } /** * 执行dml操作 * @param sql sql语句 * @param objs 参数对象 * @return */ public boolean dml(String sql, Object... objs) { try { conn = getConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { ps.setObject(i+1, objs[i]); } int flg = ps.executeUpdate(); if(flg==1) { return true; } } catch (SQLException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }finally { try { backConnection(conn,ps,rs); } catch (SQLException | InterruptedException e) { e.printStackTrace(); } } return false; } /** * 全查 * @param sql * @param objs * @return */ public JSONArray find(String sql,Object...objs){ list = new JSONArray(); try { conn = getConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { ps.setObject(i+1, objs[i]); } rs = ps.executeQuery(); md = rs.getMetaData(); while (rs.next()) { map = new JSONObject(); for (int i = 1; i <= md.getColumnCount(); i++) { String key = md.getColumnName(i); Object value = rs.getObject(i); map.put(key, value); } list.add(map); } } catch (SQLException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }finally { try { backConnection(conn,ps,rs); } catch (SQLException | InterruptedException e) { e.printStackTrace(); } } return list; } /** * 单查 * @param sql * @param objs * @return */ public JSONObject findOne(String sql,Object...objs){ JSONArray list = find(sql,objs); if(list!=null) { if(list.size()>0) { return list.getJSONObject(0); } } return null; } /** * 添加 * @param sql * @param objs * @return */ public boolean add(String sql,Object...objs) { return dml(sql, objs); } /** * 修改 * @param sql * @param objs * @return */ public boolean mod(String sql,Object...objs){ return dml(sql, objs); } /** * 删除 * @param sql * @param objs * @return */ public boolean del(String sql,Object...objs){ return dml(sql, objs); } } ``` jdbc.properties ``` db.url=jdbc:mysql://127.0.0.1:3306/juser db.user=root db.password=root driverClass=com.mysql.jdbc.Driver connectionNum=30 ```
请指教,很急,谢谢
源文件: import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.HashMap; import java.util.Map; import com.sty.hibernate.model.Student; public class Session { // ping sql 需要这些配置方法,但成员变量中不能有语句,所以写一个构造方法 String tableName = "_student"; Map<String,String> cfs=new HashMap<String,String>();//为什么用map字段名与属性名一一对应 // 因为?中有int和string的类型,插入数据的方法不统一,所以采用了hibernate的反射机制,即下面的 String[] methodName;//某个属性对应的调用某个方法名,然后存到字符数组里;String[] methordName=new String[cfs.size()]; //放在这是错误的,因为还没初始化 public Session(){ cfs.put("_id", "id");//数据库中的_id对应属性id cfs.put("_name", "name"); cfs.put("_age", "age"); methodName=new String[cfs.size()]; } //这样当调用craateSQL时map、tableName中就有值了 public void save(Student s) throws Exception { // String TableName = "_Student"; // Map<String,String> cfs=new HashMap<String,String>();//为什么用map字段名与属性名一一对应 // cfs.put("_id", "id");//数据库中的_id对应属性id // cfs.put("_name", "name"); // cfs.put("_age", "age"); // 此部分应该写在配置文件里 String sql=createSQL(); Class.forName("com.mysql.jdbc.Driver"); Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/hibernate","root","sty"); PreparedStatement ps=conn.prepareStatement(sql); for(int i=0;i<methodName.length;i++){//先拿到方法,然后执行方法,然后执行返回结果,再将其结果添加到?中去 Method m=s.getClass().getMethod(methodName[i]);//getClass()先拿到student类,getMethod(mName)将method的名字传入 Class r=m.getReturnType();//获取返回的class类型 System.out.println(r.getName()+"|"+m.getName()); if(r.getName().equals("java.lang.String")){ String returnValue=(String)m.invoke(s);//m.invoke(obj, args)因为没有参数所以省略args;m.invoke(s)返回的是object类型 ps.setString(i+1, returnValue); } if(r.getName().equals("int")){ Integer returnValue=(Integer)m.invoke(s);//m.invoke(obj, args)因为没有参数所以省略args;m.invoke(s)返回的是object类型 ps.setInt(i+1, returnValue); } } ps.executeUpdate(); ps.close(); conn.close(); } private String createSQL() { String str1=""; int index =0;//循环变量 for(String s:cfs.keySet()){ String v=cfs.get(s);//获取cfs.put("_id", "id");中value的值,即id v=Character.toUpperCase(v.charAt(0))+v.substring(1);//方法名的首字母改为大写 methodName[index]="get"+v; str1+=s+","; index++; } str1=str1.substring(0,str1.length()-1); String str2=""; for(int i=0;i<cfs.size();i++){ str2+="?,"; } str2 = str2.substring(0,str2.length()-1); String sql="insert into"+tableName+"("+str1+")"+"values ("+str2+")"; return sql; } } 问题提示: int|getId int|getAge java.lang.String|getName Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate.into_student' doesn't exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at com.mysql.jdbc.Util.getInstance(Util.java:384) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2409) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2327) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2312) at Session.save(Session.java:60) at StudentTest.main(StudentTest.java:11) 不知道是什么原因,谢谢 数据库是MySQL,其他配置正常
import com.hp.hpl.jena.db.*;报错是为什么?这是网上找的代码,运行不了
import java.io.*; import java.sql.SQLException; import com.hp.hpl.jena.db.*; import com.hp.hpl.jena.rdf.model.*; public class Persistent { public static final String strDriver = "com.mysql.jdbc.Driver"; public static final String strURL = "jdbc:mysql://localhost:3306/jena"; // localhost的后面要直接写冒号,再写3306; public static final String strUser = "root"; public static final String strPassword = "root"; public static final String strDB = "MySQL"; public static void main(String[] args){ try { DBConnection connection = new DBConnection(strURL, strUser, strPassword, strDB); // 创建连接时,第四个参数需要指定所用的数据库类型;也就是说strDB的值应该是“MySQL” try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("驱动程序已经安装。"); } catch (ClassNotFoundException e){ System.out.println("ClassNotFoundException, Driver is not available"); } System.out.println("数据库连接成功。"); // 从此处开始读入一个OWL文件并且存储到数据库中; ModelMaker maker = ModelFactory.createModelRDBMaker(connection); // 使用数据库连接参数创建一个模型制造器 Model defModel = maker.createModel("Costume"); } } // 创建一个默认模型,命名为Costume,因为我要存入的OWL文件名是Costume FileInputStream read = null; try{ File file = new File("F:/Ontology/first.owl"); read = new FileInputStream(file); }catch (FileNotFoundException e){ e.printStackTrace(); System.out.println("未找到要存储的本体文件,请检查文件地址及名称"); } System.out.println("已将本体文件转换为字节流文件。"); InputStreamReader in = null; try { in = new InputStreamReader((FileInputStream)read, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.out.println("不支持上述字符集。"); } System.out.println("已将字节流文件转换为UTF-8编码。"); defModel.read(in,null); try { in.close(); } catch (IOException e){ e.printStackTrace(); System.out.println("无法关闭字节流文件。"); } System.out.println("已将字节流文件关闭。"); defModel.commit(); System.out.println("数据转换执行完毕,已将本体文件存入数据库。"); try{ connection.close(); } catch (SQLException e){ e.printStackTrace(); System.out.println("文件无法关闭。"); } } catch (RDFRDBException e){ System.out.println("出现异常"); } System.out.println("已将本体文件持久化到数据库中"); } }
springboot 配置多库之后,mybatis在控制台不打印sql语句了
springboot项目 单库下,mybatis只需要添加如下配置,就可以打印sql语句 ```xml <!-- 打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> ``` 但是多库环境下,mybatis不论怎么设置,都无法打印sql语句..... ---- ---- 项目中的相关配置: mybatis配置: ```xml <!-- 设置运行参数 --> <settings> <!-- 全局映射器启用缓存 --> <setting name="cacheEnabled" value="true" /> <!-- 查询时,关闭关联对象及时加载以提高性能 --> <setting name="lazyLoadingEnabled" value="false" /> <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 --> <setting name="aggressiveLazyLoading" value="false" /> <!-- 对于位置的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 允许使用列标签代替列明 --> <setting name="useColumnLabel" value="true" /> <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值), 数据表的pk生成策略将被覆盖 --> <setting name="useGeneratedKeys" value="true" /> <!-- 给予被嵌套的resultMap以字段-属性的映射支持 --> <setting name="autoMappingBehavior" value="PARTIAL" /> <!-- 对于批量更新操作缓存SQL以提高性能 --> <setting name="defaultExecutorType" value="REUSE" /> <!-- 数据库超过25000秒仍未响应则超时 --> <!--<setting name="defaultStatementTimeout" value="25000" />--> <!-- 打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 开启驼峰--> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> ``` logback配置: ```xml <?xml version="1.0" encoding="UTF-8"?> <configuration scan="true"> <!-- 属性1:每个logger都关联到logger上下文,默认上下文名称为“default”。 但可以使用设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改,可以通过%contextName来打印日志上下文名称。 --> <contextName>logback</contextName> <!--属性2:定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径--> <!-- <springProfile name="dev"> <property name="LOG_PATH" value="D://care-management-statisticserver-logs"/> </springProfile> <springProfile name="test"> <property name="LOG_PATH" value="/data/tomcat_jar/taixin_care/care-management-statisticserver/logs"/> </springProfile> <springProfile name="prod"> <property name="LOG_PATH" value="/data1/logs/care-management-statisticserver"/> </springProfile> --> <property name="LOG_PATH" value="${LOG_FILE}"/> <!--appender用来格式化日志输出节点,有俩个属性name和class,class用来指定哪种输出策略,常用就是控制台输出策略和文件输出策略。--> <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>info</level> </filter> <encoder> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n</pattern> </encoder> </appender> <!--<include resource="org/springframework/boot/logging/logback/base.xml"/>--> <!-- 说明: 1、日志级别及文件 日志记录采用分级记录,级别与日志文件名相对应,不同级别的日志信息记录到不同的日志文件中 例如:error级别记录到log_error_xxx.log或log_error.log(该文件为当前记录的日志文件),而log_error_xxx.log为归档日志, 日志文件按日期记录,同一天内,若日志文件大小等于或大于2M,则按0、1、2...顺序分别命名 例如log-level-2013-12-21.0.log 其它级别的日志也是如此。 2、文件路径 若开发、测试用,在Eclipse中运行项目,则到Eclipse的安装路径查找logs文件夹,以相对路径../logs。 若部署到Tomcat下,则在Tomcat下的logs文件中 3、Appender FILEERROR对应error级别,文件名以log-error-xxx.log形式命名 FILEWARN对应warn级别,文件名以log-warn-xxx.log形式命名 FILEINFO对应info级别,文件名以log-info-xxx.log形式命名 FILEDEBUG对应debug级别,文件名以log-debug-xxx.log形式命名 CONSOLE将日志信息输出到控制上,为方便开发测试使用 --> <!-- 日志记录器,日期滚动记录 --> <appender name="FILEERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 正在记录的日志文件的路径及文件名 --> <file>${LOG_PATH}/error_statisticserver.log</file> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 归档的日志文件的路径,例如今天是2013-12-21日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。 而2013-12-21的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <fileNamePattern>${LOG_PATH}/error-statisticserver-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 表示只保留最近30天的日志,以防止日志填满整个磁盘空间。--> <maxHistory>30</maxHistory> <!--用来指定日志文件的上限大小,例如设置为1GB的话,那么到了这个值,就会删除旧的日志。--> <totalSizeCap>1GB</totalSizeCap> <!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始, 命名日志文件,例如log-error-2013-12-21.0.log --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <!-- 追加方式记录日志 --> <append>true</append> <!-- 日志文件的格式 --> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n</pattern> <charset>utf-8</charset> </encoder> <!-- 此日志文件只记录error级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- 日志记录器,日期滚动记录 --> <appender name="FILEINFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 正在记录的日志文件的路径及文件名 --> <file>${LOG_PATH}/info_statisticserver.log</file> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 归档的日志文件的路径,例如今天是2013-12-21日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。 而2013-12-21的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <fileNamePattern>${LOG_PATH}/info-statisticserver-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 表示只保留最近30天的日志,以防止日志填满整个磁盘空间。--> <maxHistory>30</maxHistory> <!--用来指定日志文件的上限大小,例如设置为1GB的话,那么到了这个值,就会删除旧的日志。--> <totalSizeCap>1GB</totalSizeCap> <!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始,命名日志文件,例如log-error-2013-12-21.0.log --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <!-- 追加方式记录日志 --> <append>true</append> <!-- 日志文件的格式 --> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n</pattern> <charset>utf-8</charset> </encoder> <!-- 此日志文件只记录info级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- <logger>用来设置某一个包或者具体的某一个类的日志打印级别、以及指定<appender>。<logger>仅有一个name属性,一个可选的level和一个可选的addtivity属性。 --> <logger name="org.springframework" level="INFO"/> <logger name="org.apache" level="ERROR"/> <logger name="org.hibernate.validator" level="ERROR"/> <!--<logger name="org.thymeleaf" level="ERROR"/>--> <logger name="org.springframework.context.annotation" level="ERROR"/> <!-- springProfile多环境日志输出,据不同环境(prod:生产环境,test:测试环境,dev:开发环境)来定义不同的日志输出--> <springProfile name="dev" /> <root level="INFO"> <appender-ref ref="FILEERROR"/> <appender-ref ref="FILEINFO"/> <appender-ref ref="STDOUT"/> </root> <!-- 可以启动服务的时候指定 profile (如不指定使用默认),如指定prod 的方式为: java -jar xxx.jar –spring.profiles.active=prod--> </configuration> ``` application.properties部分配置: ```properties #配置文件 logging.level.tk.mybatis=TRACE spring.freemarker.cache=false spring.freemarker.request-context-attribute=request mybatis.type-aliases-package=com.mtpf.domain mybatis.mapper-locations=classpath:mapper/*.xml mapper.mappers=com.mtpf.util.MyMapper mapper.not-empty=false mapper.identity=MYSQL pagehelper.helperDialect=mysql #true 是超出最大页码返回数据 false超出最大页码不返回数据 pagehelper.reasonable=${PAGEHELPER_REASONABLE} pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql ```
一开始自己配置的activiti的运行web时报错以为是环境的问题,后面到网上借鉴改了一些还是没用。
ssm框架整合activiti流程,在控制器中使用注入有关activities的一些Service如:RepositoryService、ProcessEngine、TaskService、RuntimeService、HistoryService,运行web项目后报错,后面网上借鉴了一些activitie的一些配置还是没用,o依.springframework.beans.factory.BeanCreationException: Error creating bean with name 'processEngineConfiguration' defined in file [F:\宏图软件学院办公软件项目\SchoolSystem\target\SSMTest\WEB-INF\classes\spring-activiti.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1469) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748) ``` 这个是activiti.cfg.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据源 --> <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration"> <property name="jdbcDriver" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/schoolsystem?characterEncoding=utf8"></property> <property name="jdbcUsername" value="root"></property> <property name="jdbcPassword" value="1234"></property> <property name="databaseSchemaUpdate" value="true"></property> </bean> <!-- 配置流程引擎工厂 --> <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration"></property> </bean> </beans> ``` 这个是spring-activiti.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 用于创建流程引擎的对象 --> <bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration"> <property name="transactionManager" ref="transactionManager"></property> <property name="dataSource" ref="druidDataSource"></property> <property name="databaseSchemaUpdate" value="true"></property> </bean> <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration"></property> </bean> </beans> ``` spring-dao.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置整合mybatis过程 --> <!-- 1.配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2.数据库连接池 --> <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc_driverClassName}" /> <property name="url" value="${jdbc_url}"/> <property name="username" value="${jdbc_username}"/> <property name="password" value="${jdbc_password}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="5"/> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="50"/> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20"/> <!-- 连接池最小空闲 --> <property name="minIdle" value="5"/> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000"/> <property name="validationQuery" value="${validationQuery}"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000"/> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true"/> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800"/> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true"/> <!-- 监控数据库 --> <property name="filters" value="mergeStat"/> </bean> <!-- 3.配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="druidDataSource" /> <!-- 配置MyBaties全局配置文件:mybatis-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 扫描vo包 使用别名 --> <property name="typeAliasesPackage" value="Vo" /> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:Mapper/*.xml" /> </bean> <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="Mapper"/> </bean> </beans> ``` 这个是spring-service.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="Service" /> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="druidDataSource" /> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> ``` 这个是spring-web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置spring mvc--> <!--1,开启springmvc注解模式 a.自动注册 DefaultAnnotationHandlerMapping, AnnotationMethodHandlerAdapter b.默认提供一系列的功能:数据绑定,数字和日期的format@NumberFormat,@DateTimeFormat c:xml,json的默认读写支持--> <mvc:annotation-driven conversion-service="dateUtil"></mvc:annotation-driven> <!--2.静态资源默认servlet配置--> <!-- 1).加入对静态资源处理:排除后缀 js,gif,png, 等静态资源的请求不会进入控制器 2).允许使用 "/" 做整体映射 --> <mvc:default-servlet-handler/> <!--3:配置JSP 显示ViewResolver--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4:扫描web所有的 controller--> <context:component-scan base-package="Control"/> <!-- FastJson注入 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <!-- FastJson --> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <property name="features"> <array value-type="com.alibaba.fastjson.serializer.SerializerFeature"> <!-- 避免循环引用 --> <value>DisableCircularReferenceDetect</value> <!-- 是否输出值为null的字段 --> <value>WriteMapNullValue</value> <!-- 数值字段如果为null,输出为0,而非null --> <value>WriteNullNumberAsZero</value> <!-- 字符类型字段如果为null,输出为"",而非null --> <value>WriteNullStringAsEmpty</value> <!-- List字段如果为null,输出为[],而非null --> <value>WriteNullListAsEmpty</value> <!-- Boolean字段如果为null,输出为false,而非null --> <value>WriteNullBooleanAsFalse</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <!-- 拦截URL,拦截 admin 开头的所有请求 --> <mvc:mapping path="/**" /> <!-- 添加不会被拦截的url --> <mvc:exclude-mapping path="/login/**" /> <!-- 拦截请求交给,哪个拦截器 --> <bean class="Interceptor.MyInterceptor"/> </mvc:interceptor> <!-- 国际化拦截器 --> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang"/> </bean> </mvc:interceptors> <bean id="dateUtil" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" > <property name="converters" > <list> <bean class="Base.DateUtil"></bean> </list> </property> </bean> <!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 配置文件上传最大大小(字节)这里是1M --> <property name="maxUploadSize" value="1048576"/> </bean> <!-- 国际化资源文件 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <!-- 表示多语言配置文件在根路径下,以i18n开头的文件--> <property name="basename" value="i18n"/> <property name="useCodeAsDefaultMessage" value="true"/> </bean> <!-- 配置SessionLocaleResolver用于将Locale对象存储于Session中供后续使用 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> </beans> ``` ```
在elipse上导入hibernate框架出现问题
在一开始导入hibernate框架时,导入了hibernate全部的包和c3p0数据源的包,结果在包名上产生了冲突, eclipse无法自动正确导入,把鼠标移到 import org.hibernate*.;时出现 the package org.hibernate is accessible from more than one module:hibernate.c3p0, hibernate.commons.annotations,hibernate.core; 当我把有冲突的包移除几个暂时不用的时候,没有编译错误,但运行的时候出现java.lang.NoClassDefFoundError 具体如下 Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43) at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:87) at org.hibernate.cfg.Configuration.<init>(Configuration.java:123) at org.hibernate.cfg.Configuration.<init>(Configuration.java:118) at lee.NewsManager.main(NewsManager.java:30) Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source) at java.base/java.lang.ClassLoader.loadClass(Unknown Source) ... 5 more 具体代码如下: ```package lee; import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.service.*; import org.hibernate.boot.registry.*; import org.crazyit.app.domain.New; public class NewsManager { public static void main(String[] args) throws Exception { // 实例化Configuration Configuration conf = new Configuration() // 不带参数的configure()方法默认加载hibernate.cfg.xml文件 // 如果传入abc.xml作为参数,则不再加载hibernate.cfg.xml,改为加载abc.xml .configure(); // 以Configuration实例创建SessionFactory实例 SessionFactory sf = conf.buildSessionFactory(); // 创建Session Session sess = sf.openSession(); // 开始事务 Transaction tx = sess.beginTransaction(); // 创建消息对象 New n = new New(); n.setContent( + "100"); sess.save(n); // 提交事务 tx.commit(); // 关闭Session sess.close(); sf.close(); } } package org.crazyit.app.domain; import java.util.ArrayList; import java.util.List; import javax.annotation.processing.Generated; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OrderColumn; import javax.persistence.Table; import javax.persistence.TableGenerator; @Entity @Table(name="news_inf") public class New { @TableGenerator(name="newsGen",table="NEWS_ID_GEN",pkColumnName="gen_key",valueColumnName="gen_value",pkColumnValue="new_id") @GeneratedValue(strategy=GenerationType.TABLE,generator="newsGen") private Integer id; // 消息标题 private String title; // 消息内容 private String content; @ElementCollection (targetClass=String.class) @CollectionTable(name="school_inf",joinColumns=@JoinColumn(name="person_id",nullable=false)) @Column(name="school_name") @OrderColumn(name="list_order") private List<String>schools=new ArrayList<>(); @ElementCollection (targetClass=Float.class) @CollectionTable(name="score_inf",joinColumns=@JoinColumn(name="person_id",nullable=false)) @MapKeyColumn(name="subject_name") @MapKeyClass(String.class) @Column(name="mark") // id的setter和getter方法 public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } // title的setter和getter方法 public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } @Generated(GenerationTime.ALWAYS) @Column(name="full_content") private String fullContent; // content的setter和getter方法 public void setContent(String content) { this.content = content; } public String getContent() { return this.content; } } 配置文件<?xml version="1.0" encoding="GBK"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 指定连接数据库所用的驱动 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 --> <property name="connection.url">jdbc:mysql://localhost/hibernate?useSSL=true</property> <!-- 指定连接数据库的用户名 --> <property name="connection.username">root</property> <!-- 指定连接数据库的密码 --> <property name="connection.password">ak474247152919</property> <!-- 指定连接池里最大连接数 --> <property name="hibernate.c3p0.max_size">20</property> <!-- 指定连接池里最小连接数 --> <property name="hibernate.c3p0.min_size">1</property> <!-- 指定连接池里连接的超时时长 --> <property name="hibernate.c3p0.timeout">5000</property> <!-- 指定连接池里最大缓存多少个Statement对象 --> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.validate">true</property> <!-- 指定数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- 根据需要自动创建数据表 --> <property name="hbm2ddl.auto">update</property><!--①--> <!-- 显示Hibernate持久化操作所生成的SQL --> <property name="show_sql">true</property> <!-- 将SQL脚本进行格式化后再输出 --> <property name="hibernate.format_sql">true</property> <!-- 罗列所有持久化类的类名 --> <mapping class="org.crazyit.app.domain.News"/> </session-factory> </hibernate-configuration> ```
求助 小白debug不到是哪空指针了。
public class MainActivity extends Activity { private GraphicalView chart; private Timer timer = new Timer(); private TimerTask task; private Float addY; private String addX; Tool_Sqls mysql = new Tool_Sqls(); String[] xkedu = new String[20] ;//x轴数据缓冲 Float[] ycache = new Float[20]; //private final static int SERISE_NR = 1; //曲线数量 private XYSeries series;//用来清空第一个再加下一个 private XYMultipleSeriesDataset dataset1;//xy轴数据源 private XYMultipleSeriesRenderer render; SimpleDateFormat shijian = new SimpleDateFormat("hh:mm:ss"); Handler handler2; TextView guangzhi2; protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.guangzhao); //guangzhi2=(TextView)findViewById(R.id.guangzhi2); //制作曲线图 LinearLayout linearLayout = (LinearLayout)findViewById(R.id.guangzhexian); chart = ChartFactory.getLineChartView(this, getdemodataset(), getdemorenderer()); linearLayout.removeAllViews();//先remove再add可以实现统计图更新 linearLayout.addView(chart, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); handler2 = new Handler(){ public void handleMessage(Message msg) { updatechart(); //guangzhi2.setText(String.valueOf(addY)); } }; task = new TimerTask(){ public void run() { Message msg=new Message(); msg.what=200; handler2.sendMessage(msg); } }; timer.schedule(task, 0, 2000); }//oncreate结束 //更新折线图 private void updatechart() { //判断当前点集中到底有多少点,因为屏幕总共只能容纳20个,所以当点数超过20时,长度永远是20 int length=series.getItemCount(); int a=length; if(length>20){ length=20; } // try { // if(guangzhi2.getText().toString()!=null){ // addY = Float.valueOf(guangzhi2.getText().toString());//要不要判断再说 // } // } catch (NumberFormatException e) { // e.printStackTrace(); // } addX=shijian.format(new java.util.Date()); try { mysql.getROID_4("hoestry2","id"); while (mysql.rs.next()) { addY = Float.valueOf(mysql.rs.getFloat("outlet_temperature"));//(float)(Math.random()*10); } mysql.rs.close(); mysql.stmt.close(); mysql.con.close(); } catch (SQLException e) { e.printStackTrace(); } //移除数据集中旧的点集 dataset1.removeSeries(series); if(a<20)//当数据集中不够20个点的时候直接添加就好,因为初始化的时候只有一个点,所以前几次更新的时候直接添加 { series.add(a+1, addY);//第一个参数代表第几个点,要与下面语句中的第一个参数对应 render.addXTextLabel(a+1, addX); xkedu[a]=addX; } else //超过了20个点要去除xcache【0】换成【1】的..... { //将旧的点集中x和y的数值取出来放入backup中,造成曲线向左平移的效果 for(int i =0 ;i<length-1;i++){ ycache[i]=(float) series.getY(i+1); xkedu[i]=xkedu[i+1]; } //点集先清空,为了做成新的点集而准备 series.clear(); //将新产生的点首先加入到点集中,然后在循环体中将坐标变换后的一系列点都重新加入到点集中 for(int k =0 ;k<length-1;k++){ series.add(k+1, ycache[k]); render.addXTextLabel(k+1, xkedu[k]); } xkedu[4]=addX; series.add(20, addY); render.addXTextLabel(20, addX); } //在数据集中添加新的点集 dataset1.addSeries(series); //视图更新,没有这一步,曲线不会呈现动态 chart.invalidate(); } private XYMultipleSeriesRenderer getdemorenderer() { // TODO Auto-generated method stub render = new XYMultipleSeriesRenderer(); render.setChartTitle("三新锅炉温度曲线图"); render.setChartTitleTextSize(20);//设置整个图表标题文字的大小 render.setAxisTitleTextSize(16);//设置轴标题文字的大小 render.setAxesColor(Color.BLACK); render.setXTitle("时间/hh:mm:ss"); render.setYTitle("温度/℃"); render.setLabelsTextSize(16);//设置轴刻度文字的大小 render.setLabelsColor(Color.BLACK); render.setXLabelsColor(Color.BLACK); render.setYLabelsColor(0, Color.BLACK); render.setLegendTextSize(15);//设置图例文字大小 //render.setShowLegend(false);//显示不显示在这里设置,非常完美 XYSeriesRenderer r = new XYSeriesRenderer();//设置颜色和点类型 r.setColor(Color.RED); r.setPointStyle(PointStyle.CIRCLE); r.setFillPoints(true); r.setChartValuesSpacing(3); render.addSeriesRenderer(r); render.setYLabelsAlign(Align.RIGHT);//刻度值相对于刻度的位置 render.setShowGrid(true);//显示网格 render.setYAxisMax(60);//设置y轴的范围 render.setYAxisMin(-10); render.setYLabels(20);//设置Y轴标签数 render.setDisplayChartValues(true);//设置Y轴曲线上的点的数值是否显示,实测当点数密集的时候不会全部显示,会隔一段时间显示 render.setInScroll(true); render.setLabelsTextSize(14); render.setLabelsColor(Color.BLACK); //render.getSeriesRendererAt(0).setDisplayChartValues(true); //显示折线上点的数值 render.setPanEnabled(false,false);//禁止报表的拖动 render.setPointSize(5f);//设置点的大小(图上显示的点的大小和图例中点的大小都会被设置) render.setMargins(new int[]{40,40,40,40}); //设置图形四周的留白 render.setMarginsColor(Color.WHITE); render.setXLabels(0);// 取消X坐标的数字zjk,只有自己定义横坐标是才设为此值 return render; } private XYMultipleSeriesDataset getdemodataset() { // TODO Auto-generated method stub dataset1=new XYMultipleSeriesDataset();//xy轴数据源 series = new XYSeries("矿大温度 ");//这个事是显示多条用的,显不显示在上面render设置 //这里相当于初始化,初始化中无需添加数据,因为如果这里添加第一个数据的话, //很容易使第一个数据和定时器中更新的第二个数据的时间间隔不为两秒,所以下面语句屏蔽 //这里可以一次更新五个数据,这样的话相当于开始的时候就把五个数据全部加进去了,但是数据的时间是不准确或者间隔不为二的 //for(int i=0;i<5;i++) //series.add(1, Math.random()*10);//横坐标date数据类型,纵坐标随即数等待更新 dataset1.addSeries(series); return dataset1; } public void onDestroy() { //当结束程序时关掉Timer timer.cancel(); super.onDestroy(); } } ``` ```
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小人工智障。 思路可以运用在不同地方,主要介绍的是思路。
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
阿里面试官问我:如何设计秒杀系统?我的回答让他比起大拇指
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图和个人联系方式,欢迎Star和指教 前言 Redis在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在Redis的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸,打败了...
C语言魔塔游戏
很早就很想写这个,今天终于写完了。 游戏截图: 编译环境: VS2017 游戏需要一些图片,如果有想要的或者对游戏有什么看法的可以加我的QQ 2985486630 讨论,如果暂时没有回应,可以在博客下方留言,到时候我会看到。 下面我来介绍一下游戏的主要功能和实现方式 首先是玩家的定义,使用结构体,这个名字是可以自己改变的 struct gamerole { char n...
面试官问我:什么是消息队列?什么场景需要他?用了会出现什么问题?
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
Android性能优化(4):UI渲染机制以及优化
文章目录1. 渲染机制分析1.1 渲染机制1.2 卡顿现象1.3 内存抖动2. 渲染优化方式2.1 过度绘制优化2.1.1 Show GPU overdraw2.1.2 Profile GPU Rendering2.2 卡顿优化2.2.1 SysTrace2.2.2 TraceView 在从Android 6.0源码的角度剖析View的绘制原理一文中,我们了解到View的绘制流程有三个步骤,即m...
微服务中的Kafka与Micronaut
今天,我们将通过Apache Kafka主题构建一些彼此异步通信的微服务。我们使用Micronaut框架,它为与Kafka集成提供专门的库。让我们简要介绍一下示例系统的体系结构。我们有四个微型服务:订单服务,行程服务,司机服务和乘客服务。这些应用程序的实现非常简单。它们都有内存存储,并连接到同一个Kafka实例。 我们系统的主要目标是为客户安排行程。订单服务应用程序还充当网关。它接收来自客户的请求...
致 Python 初学者们!
作者| 许向武 责编 | 屠敏 出品 | CSDN 博客 前言 在 Python 进阶的过程中,相信很多同学应该大致上学习了很多 Python 的基础知识,也正在努力成长。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 Python 这门编程语言,从2009年开始单一使用 Python 应对所有的开发工作,直至今...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观...
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外...
字节跳动面试官这样问消息队列:分布式事务、重复消费、顺序消费,我整理了一下
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip installselenium -ihttps://pypi.tuna.tsinghua.edu.cn/simple/ ...
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca...
SpringBoot2.x系列教程(三十六)SpringBoot之Tomcat配置
Spring Boot默认内嵌的Tomcat为Servlet容器,关于Tomcat的所有属性都在ServerProperties配置类中。同时,也可以实现一些接口来自定义内嵌Servlet容器和内嵌Tomcat等的配置。 关于此配置,网络上有大量的资料,但都是基于SpringBoot1.5.x版本,并不适合当前最新版本。本文将带大家了解一下最新版本的使用。 ServerProperties的部分源...
Python绘图,圣诞树,花,爱心 | Turtle篇
每周每日,分享Python实战代码,入门资料,进阶资料,基础语法,爬虫,数据分析,web网站,机器学习,深度学习等等。 公众号回复【进群】沟通交流吧,QQ扫码进群学习吧 微信群 QQ群 1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle()...
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东...
破14亿,Python分析我国存在哪些人口危机!
一、背景 二、爬取数据 三、数据分析 1、总人口 2、男女人口比例 3、人口城镇化 4、人口增长率 5、人口老化(抚养比) 6、各省人口 7、世界人口 四、遇到的问题 遇到的问题 1、数据分页,需要获取从1949-2018年数据,观察到有近20年参数:LAST20,由此推测获取近70年的参数可设置为:LAST70 2、2019年数据没有放上去,可以手动添加上去 3、将数据进行 行列转换 4、列名...
听说想当黑客的都玩过这个Monyer游戏(1~14攻略)
第零关 进入传送门开始第0关(游戏链接) 请点击链接进入第1关: 连接在左边→ ←连接在右边 看不到啊。。。。(只能看到一堆大佬做完的留名,也能看到菜鸡的我,在后面~~) 直接fn+f12吧 &lt;span&gt;连接在左边→&lt;/span&gt; &lt;a href="first.php"&gt;&lt;/a&gt; &lt;span&gt;←连接在右边&lt;/span&gt; o...
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ...... ...
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。 再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。 下文是原回答,希望能对你能有所启发。 如果我说,这个世界上人真的分三六九等,...
2020年全新Java学习路线图,含配套视频,学完即为中级Java程序员!!
新的一年来临,突如其来的疫情打破了平静的生活! 在家的你是否很无聊,如果无聊就来学习吧! 世上只有一种投资只赚不赔,那就是学习!!! 传智播客于2020年升级了Java学习线路图,硬核升级,免费放送! 学完你就是中级程序员,能更快一步找到工作! 一、Java基础 JavaSE基础是Java中级程序员的起点,是帮助你从小白到懂得编程的必经之路。 在Java基础板块中有6个子模块的学...
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合...
爬取薅羊毛网站百度云资源
这是疫情期间无聊做的爬虫, 去获取暂时用不上的教程 import threading import time import pandas as pd import requests import re from threading import Thread, Lock # import urllib.request as request # req=urllib.request.Requ...
如何优雅地打印一个Java对象?
你好呀,我是沉默王二,一个和黄家驹一样身高,和刘德华一样颜值的程序员。虽然已经写了十多年的 Java 代码,但仍然觉得自己是个菜鸟(请允许我惭愧一下)。 在一个月黑风高的夜晚,我思前想后,觉得再也不能这么蹉跎下去了。于是痛下决心,准备通过输出的方式倒逼输入,以此来修炼自己的内功,从而进阶成为一名真正意义上的大神。与此同时,希望这些文章能够帮助到更多的读者,让大家在学习的路上不再寂寞、空虚和冷。 ...
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名...
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计...
HTML5适合的情人节礼物有纪念日期功能
前言 利用HTML5,css,js实现爱心树 以及 纪念日期的功能 网页有播放音乐功能 以及打字倾诉感情的画面,非常适合情人节送给女朋友 具体的HTML代码 具体只要修改代码里面的男某某和女某某 文字段也可自行修改,还有代码下半部分的JS代码需要修改一下起始日期 注意月份为0~11月 也就是月份需要减一。 当然只有一部分HTML和JS代码不够运行的,文章最下面还附加了完整代码的下载地址 &lt;!...
相关热词 c# 识别回车 c#生成条形码ean13 c#子控制器调用父控制器 c# 写大文件 c# 浏览pdf c#获取桌面图标的句柄 c# list反射 c# 句柄 进程 c# 倒计时 线程 c# 窗体背景色
立即提问