Java连接mysql实现查询功能中,mysql date 类型转换换问题。

1424人阅读
Resultset中的所有数据都可以通过getString()方法取得
String是可以接收表中的任意类型列的内容,所以在以下的程序中全部都使用getString()接收
package JDBC;
import java.sql.*;
public class MySQLquery {
public static final String DRIVER = &com.mysql.jdbc.Driver&;&
public static final String URL = &jdbc:mysql://127.0.0.1:3306/lianxi&; &&
public static final String USERNAME = &root&; &
public static final String PASSWORD = &123456&;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection conn = //每一个Connection对象表示一个数据库连接对象
Statement stat =
Class.forName(DRIVER);//加载驱动程序
conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
stat = conn.createStatement();//找到借口
String sql = &select*from hehe&;//查询语句
ResultSet rs=stat.executeQuery(sql);//查询
//将查询出的结果输出
while (rs.next()) {
String deptno=rs.getString(&deptno&);
String dname=rs.getString(&dname&);
String loc=rs.getString(&loc&);
下列三行语句与上面三行语句作用相同,仅需一个就行
String deptno=rs.getString(1);
String dname=rs.getString(2);
String loc=rs.getString(3);
System.out.println(&deptno:&+deptno+&,dname:&+dname+&,loc:&+loc);
rs.close();
stat.close();
conn.close();
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:4593次
排名:千里之外
原创:26篇
转载:10篇
(1)(1)(17)(17)怎么用java转换mysql数据类型_百度知道
怎么用java转换mysql数据类型
我有更好的答案
java中Date值得格式是是&#39:mm:ss'YYYY-MM-DD HHmysql DATE值的格式是'YYYY-MM-DD&#39
【0元入学,两周免费试听】
主营:培训【Python+人工智能,Java大数据,HTML5】
多数数据类型都一样,个别的稍微转换一下,需要快捷键点下就能找到了
啥玩意,说详细点
为您推荐:
其他类似问题
您可能关注的内容
mysql的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。随笔- 279&
//方法一,可以验证登录,但方法不实用。package com.
import java.sql.C
import java.sql.DriverM
import java.sql.ResultS
import java.sql.SQLE
import java.sql.S
import java.util.ArrayL
import java.util.L
public class LoginJDBC {
public static void main(String[] args) {
User userZhangsan=new User("swift","123456");
if(login(userZhangsan)) {
System.out.println("登陆成功");
System.out.println("登陆失败");
private static boolean login(User userZhangsan) {
Connection conn=null;
Statement st=null;
ResultSet rs=null;
//<span style="color: #、装载驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
//<span style="color: #、链接数据库,使用com.mysql.jdbc.Connection包会出错
List&User& list=new ArrayList&User&();
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sw_database?user=root&password=root");
//<span style="color: #、创建连接语句
st=conn.createStatement();
//<span style="color: #、执行SQL语句获得结果集
rs=st.executeQuery("select * from sw_user");
//<span style="color: #、循环获得数据库字段生成对象
//这种方法登录要把数据库数据都拿过来和login中数据比较,超级浪费资源
while(rs.next()) {
String username=rs.getString("username");
String password=rs.getString("password");
if(username.equals(userZhangsan.getUsername())&&password.equals(userZhangsan.getPassword())) {
return true;
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//关闭结果集
if(rs!=null) {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//关闭连接语句
if(st!=null) {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//关闭数据库连接
if(conn!=null) {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
方法二 使用数据库查询语句 select * from sw_user where username='swift' and password='123456'
在Java程序中注意单引号''是不可缺少的,它是sql语句自带部分,双引号是Java的字符串连接符,所以要了解"" ''各自的作用
package com.
import java.sql.C
import java.sql.DriverM
import java.sql.ResultS
import java.sql.SQLE
import java.sql.S
import java.util.ArrayL
import java.util.L
public class LoginJDBC2 {
public static void main(String[] args) {
User userZhangsan=new User("zhangsan","123456");
if(login(userZhangsan)) {
System.out.println("登陆成功");
System.out.println("登陆失败");
private static boolean login(User userZhangsan) {
Connection conn=null;
Statement st=null;
ResultSet rs=null;
//<span style="color: #、装载驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
//<span style="color: #、链接数据库,使用com.mysql.jdbc.Connection包会出错
List&User& list=new ArrayList&User&();
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sw_database?user=root&password=root");
//<span style="color: #、创建连接语句
st=conn.createStatement();
//<span style="color: #、执行SQL语句获得结果集
rs=st.executeQuery("select * from sw_user where username='"+userZhangsan.getUsername()+"' and password='"+userZhangsan.getPassword()+"'");
//<span style="color: #、循环获得数据库字段生成对象
//这种方法登录要把数据库数据都拿过来和login中数据比较,超级浪费资源
if(rs.next()) {
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//关闭结果集
if(rs!=null) {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//关闭连接语句
if(st!=null) {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//关闭数据库连接
if(conn!=null) {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
阅读(...) 评论()Java语言实现对MySql数据库中数据的增删改查操作的代码
转载 & & 作者:i逆天耗子丶
这篇文章主要介绍了Java语言实现对MySql数据库中数据的增删改查操作的代码,实现了连接数据库,和数据库的增删改查操作,有兴趣的可以了解一下。
简单说操作的步骤:
1.连接数据库
2.将SQL语句发送到数据库
3.执行SQL语句
这里举个例子:
在一个数据库中有个students表,表中有学号(Id),姓名(Name),性别(Sex),地址(Address),电话(Phone),专业(Dept)。
这里把这个表写成一个学生信息类(Info_student)
(请先确保看了例子说明,不然代码有的地方可能看不明白)
要实现操纵我们首先得连接数据库,因为每个操作都要进行连接操作,所以我们直接把连接的操作封装在一个类中,需要连接的时候直接调用可。
数据库连接类:
import java.sql.C
import java.sql.DriverM
public class DB_Helper {
public static Connection connect =
Class.forName("com.mysql.jdbc.Driver"); // 加载MYSQL JDBC驱动程序
// 观察以下2个语句的差别,
// connect =
// DriverManager.getConnection("jdbc:mysql://localhost:3306/students", "root", "");
connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/students&#63;useUnicode=true&characterEncoding=utf-8", "root", "");
System.out.println("Success loading Mysql Driver!");
} catch (Exception e) {
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
public static Connection getConnection() {
数据库已经连接了,那么接下来就是要发送SQL语句和执行语句。
发送语句用到了PreparedStatement对象和Connection对象的操作prepareStatement()
执行语句用到PreparedStatement对象的操作execute()
提示:以下是一些对象的说明,可以先看代码,遇到的时候再回来看。
************************
PreparedStatement
表示预编译的 SQL 语句的对象。
SQL 语句被预编译并存储在 PreparedStatement 对象中。然后可以使用此对象多次高效地执行该语句。
*************************
Connection
与特定数据库的连接(会话)。在连接上下文中执行 SQL 语句并返回结果。
Connection 对象的数据库能够提供描述其表、所支持的 SQL 语法、存储过程、此连接功能等等的信息。
**********************
以下代码是要实现在数据库中实现学生信息的增删改查操作。
public void add(Info_student student) throws SQLException{
// 与特定数据库的连接(会话)。
Connection conn = (Connection) DB_Helper.getConnection();
String sql = "insert into student(Sno,Sname,Ssex,Saddress,Sphone,Sdept) values(&#63;,&#63;,&#63;,&#63;,&#63;,&#63;)";
// 创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库。
PreparedStatement ptmt = (PreparedStatement) conn.prepareStatement(sql);
* void setBigDecimal(int parameterIndex,BigDecimal x)throws SQLException
* 将指定参数设置为给定 Java String 值。在将此值发送给数据库时,驱动程序将它转换成一个 SQL VARCHAR
* 或 LONGVARCHAR 值(取决于该参数相对于驱动程序在 VARCHAR 值上的限制的大小)。
ptmt.setString(1, student.getId());
ptmt.setString(2, student.getName());
ptmt.setString(3, student.getSex());
ptmt.setString(4, student.getAddress());
ptmt.setString(5, student.getPhone());
ptmt.setString(6, student.getDept());
// 在此 PreparedStatement 对象中执行 SQL 语句
ptmt.execute();
public void delete(String id) throws SQLException{
Connection conn = (Connection) DB_Helper.getConnection();
String sql = "delete from student where Sno=&#63;";
PreparedStatement ptmt = (PreparedStatement) conn.prepareStatement(sql);
ptmt.setString(1, id);
ptmt.execute();
public void update(Info_student student) throws SQLException{
Connection conn = (Connection) DB_Helper.getConnection();
String sql = "update student set Sname=&#63;,Ssex=&#63;,Saddress=&#63;,Sphone=&#63;,Sdept=&#63; where Sno=&#63;";
PreparedStatement ptmt = (PreparedStatement) conn.prepareStatement(sql);
ptmt.setString(1, student.getName());
ptmt.setString(2, student.getSex());
ptmt.setString(3, student.getAddress());
ptmt.setString(4, student.getPhone());
ptmt.setString(5, student.getDept());
ptmt.setString(6, student.getId());
ptmt.execute();
public Info_student search(String id) throws SQLException{
Info_student student =
Connection conn = (Connection) DB_Helper.getConnection();
String sql = "select * from student where Sno=&#63;";
PreparedStatement ptmt = (PreparedStatement) conn.prepareStatement(sql);
ptmt.setString(1, id);
* ResultSet executeQuery()throws SQLException
* 在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象。
* public interface ResultSet extends Wrapper
* 表示数据库结果集的数据表,通常通过执行查询数据库的语句生成。 ResultSet 对象具有指向其当前数据行的光标。
* 最初,光标被置于第一行之前。next 方法将光标移动到下一行;因为该方法在 ResultSet 对象没有下一行时
* 返回 false,所以可以在 while 循环中使用它来迭代结果集。
ResultSet rs = ptmt.executeQuery();
* boolean next()throws SQLException
* 将光标从当前位置向前移一行。
* ResultSet 光标最初位于第一行之前;
* 第一次调用 next 方法使第一行成为当前行;
* 第二次调用使第二行成为当前行,依此类推。
while(rs.next()){
student = new Info_student();
student.setId(rs.getString("Sno"));
student.setName(rs.getString("Sname"));
student.setSex(rs.getString("Ssex"));
student.setAddress(rs.getString("Saddress"));
student.setPhone(rs.getString("Sphone"));
student.setDept(rs.getString("Sdept"));
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具实例讲解Java的MyBatis框架对MySQL中数据的关联查询
转载 & & 作者:亦山
这里我们来以实例讲解Java的MyBatis框架对MySQL中数据的关联查询,包括一对多、多对一的关联查询以及自身关联映射的方法等,需要的朋友可以参考下
mybatis 提供了高级的关联查询功能,可以很方便地将数据库获取的结果集映射到定义的Java Bean 中。下面通过一个实例,来展示一下Mybatis对于常见的一对多和多对一关系复杂映射是怎样处理的。
设计一个简单的博客系统,一个用户可以开多个博客,在博客中可以发表文章,允许发表评论,可以为文章加标签。博客系统主要有以下几张表构成:
Author表:作者信息表,记录作者的信息,用户名和密码,邮箱等。
Blog表&& :& 博客表,一个作者可以开多个博客,即Author和Blog的关系是一对多。
Post表& : 文章记录表,记录文章发表时间,标题,正文等信息;一个博客下可以有很多篇文章,Blog 和Post的关系是一对多。
Comments表:文章评论表,记录文章的评论,一篇文章可以有很多个评论:Post和Comments的对应关系是一对多。
Tag表:标签表,表示文章的标签分类,一篇文章可以有多个标签,而一个标签可以应用到不同的文章上,所以Tag和Post的关系是多对多的关系;(Tag和Post的多对多关系通过Post_Tag表体现)
Post_Tag表: 记录 文章和标签的对应关系。
一般情况下,我们会根据每一张表的结构 创建与此相对应的JavaBean(或者Pojo),来完成对表的基本CRUD操作。
上述对单个表的JavaBean定义有时候不能满足业务上的需求。在业务上,一个Blog对象应该有其作者的信息和一个文章列表,如下图所示:
如果想得到这样的类的实例,则最起码要有一下几步:
1. 通过Blog 的id 到Blog表里查询Blog信息,将查询到的blogId 和title 赋到Blog对象内;
2. 根据查询到到blog信息中的authorId 去 Author表获取对应的author信息,获取Author对象,然后赋到Blog对象内;
3. 根据 blogId 去 Post表里查询 对应的 Post文章列表,将List&Post&对象赋到Blog对象中;
这样的话,在底层最起码调用三次查询语句,请看下列的代码:
* 通过blogId获取BlogInfo对象
public static BlogInfo ordinaryQueryOnTest(String blogId)
BigDecimal id = new BigDecimal(blogId);
SqlSession session = sqlSessionFactory.openSession();
BlogInfo blogInfo = new BlogInfo();
//1.根据blogid 查询Blog对象,将值设置到blogInfo中
Blog blog = (Blog)session.selectOne("com.foo.bean.BlogMapper.selectByPrimaryKey",id);
blogInfo.setBlogId(blog.getBlogId());
blogInfo.setTitle(blog.getTitle());
//2.根据Blog中的authorId,进入数据库查询Author信息,将结果设置到blogInfo对象中
Author author = (Author)session.selectOne("com.foo.bean.AuthorMapper.selectByPrimaryKey",blog.getAuthorId());
blogInfo.setAuthor(author);
//3.查询posts对象,设置进blogInfo中
List posts = session.selectList("com.foo.bean.PostMapper.selectByBlogId",blog.getBlogId());
blogInfo.setPosts(posts);
//以JSON字符串的形式将对象打印出来
JSONObject object = new JSONObject(blogInfo);
System.out.println(object.toString());
return blogI
从上面的代码可以看出,想获取一个BlogInfo对象比较麻烦,总共要调用三次数据库查询,得到需要的信息,然后再组装BlogInfo对象。
嵌套语句查询
mybatis提供了一种机制,叫做嵌套语句查询,可以大大简化上述的操作,加入配置及代码如下:
&resultMap type="com.foo.bean.BlogInfo" id="BlogInfo"&
&id column="blog_id" property="blogId" /&
&result column="title" property="title" /&
&association property="author" column="blog_author_id"
javaType="com.foo.bean.Author" select="com.foo.bean.AuthorMapper.selectByPrimaryKey"&
&/association&
&collection property="posts" column="blog_id" ofType="com.foo.bean.Post"
select="com.foo.bean.PostMapper.selectByBlogId"&
&/collection&
&/resultMap&
&select id="queryBlogInfoById" resultMap="BlogInfo" parameterType="java.math.BigDecimal"&
B.BLOG_ID,
B.AUTHOR_ID AS BLOG_AUTHOR_ID
FROM LOULUAN.BLOG B
where B.BLOG_ID = #{blogId,jdbcType=DECIMAL}
* 通过blogId获取BlogInfo对象
public static BlogInfo nestedQueryOnTest(String blogId)
BigDecimal id = new BigDecimal(blogId);
SqlSession session = sqlSessionFactory.openSession();
BlogInfo blogInfo = new BlogInfo();
blogInfo = (BlogInfo)session.selectOne("com.foo.bean.BlogMapper.queryBlogInfoById",id);
JSONObject object = new JSONObject(blogInfo);
System.out.println(object.toString());
return blogI
通过上述的代码完全可以实现前面的那个查询。这里我们在代码里只需要 blogInfo = (BlogInfo)session.selectOne("com.foo.bean.BlogMapper.queryBlogInfoById",id);一句即可获取到复杂的blogInfo对象。
嵌套语句查询的原理
在上面的代码中,Mybatis会执行以下流程:
1.先执行 queryBlogInfoById 对应的语句从Blog表里获取到ResultSet结果集;
2.取出ResultSet下一条有效记录,然后根据resultMap定义的映射规格,通过这条记录的数据来构建对应的一个BlogInfo 对象。
3. 当要对BlogInfo中的author属性进行赋值的时候,发现有一个关联的查询,此时Mybatis会先执行这个select查询语句,得到返回的结果,将结果设置到BlogInfo的author属性上;
4. 对BlogInfo的posts进行赋值时,也有上述类似的过程。
5. 重复2步骤,直至ResultSet. next () == false;
以下是blogInfo对象构造赋值过程示意图:
这种关联的嵌套查询,有一个非常好的作用就是:可以重用select语句,通过简单的select语句之间的组合来构造复杂的对象。上面嵌套的两个select语句com.foo.bean.AuthorMapper.selectByPrimaryKey和com.foo.bean.PostMapper.selectByBlogId完全可以独立使用。
它的弊端也比较明显:即所谓的N+1问题。关联的嵌套查询显示得到一个结果集,然后根据这个结果集的每一条记录进行关联查询。
现在假设嵌套查询就一个(即resultMap 内部就一个association标签),现查询的结果集返回条数为N,那么关联查询语句将会被执行N次,加上自身返回结果集查询1次,共需要访问数据库N+1次。如果N比较大的话,这样的数据库访问消耗是非常大的!所以使用这种嵌套语句查询的使用者一定要考虑慎重考虑,确保N值不会很大。
以上面的例子为例,select 语句本身会返回com.foo.bean.BlogMapper.queryBlogInfoById 条数为1 的结果集,由于它有两条关联的语句查询,它需要共访问数据库 1*(1+1)=3次数据库。
嵌套结果查询
嵌套语句的查询会导致数据库访问次数不定,进而有可能影响到性能。Mybatis还支持一种嵌套结果的查询:即对于一对多,多对多,多对一的情况的查询,Mybatis通过联合查询,将结果从数据库内一次性查出来,然后根据其一对多,多对一,多对多的关系和ResultMap中的配置,进行结果的转换,构建需要的对象。
重新定义BlogInfo的结果映射 resultMap
&resultMap type="com.foo.bean.BlogInfo" id="BlogInfo"&
&id column="blog_id" property="blogId"/&
&result column="title" property="title"/&
&association property="author" column="blog_author_id" javaType="com.foo.bean.Author"&
&id column="author_id" property="authorId"/&
&result column="user_name" property="userName"/&
&result column="password" property="password"/&
&result column="email" property="email"/&
&result column="biography" property="biography"/&
&/association&
&collection property="posts" column="blog_post_id" ofType="com.foo.bean.Post"&
&id column="post_id" property="postId"/&
&result column="blog_id" property="blogId"/&
&result column="create_time" property="createTime"/&
&result column="subject" property="subject"/&
&result column="body" property="body"/&
&result column="draft" property="draft"/&
&/collection&
&/resultMap&
对应的sql语句如下:
&select id="queryAllBlogInfo" resultMap="BlogInfo"&
B.BLOG_ID,
B.AUTHOR_ID AS BLOG_AUTHOR_ID,
A.AUTHOR_ID,
A.USER_NAME,
A.PASSWORD,
A.BIOGRAPHY,
P.POST_ID,
P.BLOG_ID AS BLOG_POST_ID ,
P.CREATE_TIME,
P.SUBJECT,
FROM BLOG B
LEFT OUTER JOIN AUTHOR A
ON B.AUTHOR_ID = A.AUTHOR_ID
LEFT OUTER JOIN POST P
ON P.BLOG_ID = B.BLOG_ID
* 获取所有Blog的所有信息
public static BlogInfo nestedResultOnTest()
SqlSession session = sqlSessionFactory.openSession();
BlogInfo blogInfo = new BlogInfo();
blogInfo = (BlogInfo)session.selectOne("com.foo.bean.BlogMapper.queryAllBlogInfo");
JSONObject object = new JSONObject(blogInfo);
System.out.println(object.toString());
return blogI
嵌套结果查询的执行步骤:
1.根据表的对应关系,进行join操作,获取到结果集;
2. 根据结果集的信息和BlogInfo 的resultMap定义信息,对返回的结果集在内存中进行组装、赋值,构造BlogInfo;
3. 返回构造出来的结果List&BlogInfo& 结果。
对于关联的结果查询,如果是多对一的关系,则通过形如 &association property="author" column="blog_author_id" javaType="com.foo.bean.Author"& 进行配置,Mybatis会通过column属性对应的author_id 值去从内存中取数据,并且封装成Author对象;
如果是一对多的关系,就如Blog和Post之间的关系,通过形如 &collection property="posts" column="blog_post_id" ofType="com.foo.bean.Post"&进行配置,MyBatis通过 blog_Id去内存中取Post对象,封装成List&Post&;
对于关联结果的查询,只需要查询数据库一次,然后对结果的整合和组装全部放在了内存中。
以上是通过查询Blog所有信息来演示了一对多和多对一的映射对象处理。
ps:自身关联映射示例:
public class Module {
private Module parentM
private List&Module& childrenM
public int getId() {
public void setId(int id) {
public String getKey() {
public void setKey(String key) {
this.key =
public String getName() {
public void setName(String name) {
this.name =
public Module getParentModule() {
return parentM
public void setParentModule(Module parentModule) {
this.parentModule = parentM
public String getUrl() {
public void setUrl(String url) {
this.url =
public int getSort() {
public void setSort(int sort) {
this.sort =
public String getShow() {
public void setShow(String show) {
this.show =
public String getDel() {
public void setDel(String del) {
this.del =
public List&Module& getChildrenModules() {
return childrenM
public void setChildrenModules(List&Module& childrenModules) {
this.childrenModules = childrenM
&mapper namespace="com.sagaware.caraccess.mapper.ModuleMapper"&
&resultMap type="Module" id="moduleResultMap"&
&id property="id" column="module_id"/&
&result property="key" column="module_key"/&
&result property="name" column="module_name"/&
&result property="url" column="module_url"/&
&result property="sort" column="module_sort"/&
&result property="show" column="module_show"/&
&result property="del" column="module_del"/&
&!-- 查询父模块 --&
&association property="parentModule" column="module_parent_id" select="getModulesById" /&
&!-- 查询子模块 --&
&collection property="childrenModules" column="module_id" select="getChildrenModues" /&
&/resultMap&
&select id="getModules" parameterType="String" resultMap="moduleResultMap"&
select * from tb_module where module_id=2
&select id="getModulesById" parameterType="int" resultMap="moduleResultMap"&
select * from tb_module where module_id = #{module_id}
&select id="getChildrenModues" parameterType="int" resultMap="moduleResultMap"&
select * from tb_module where module_parent_id = #{module_id}
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 mysql date 类型转换 的文章

 

随机推荐