不知道数据库中表的列类型的前提下,使用JDBC正确的取出数据
概要: 使用jdbc 如果在不知道表结构的情况下,如何读出表信息?
使用ResultSetMetaData;
然后使用getColumnType 获取column 类型
使用getColumnName 获取column名字
根据类型,使用ResultSet 的getInt("column1")....获取每个字段的值
本文使用 Vector 做为容器,把拿到的查询结果,临时放在容器内。
1. 数据库准备
a. create database study;
b. create table
CREATE TABLE `test` ( `id` int(11) NOT NULL DEFAULT '', `name` varchar(10) DEFAULT NULL,
`birthday` datetime DEFAULT NULL, `score` double DEFAULT NULL, `info` text,
PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
mysql> desc test;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | 0 | |
| name | varchar(10) | YES | | NULL | |
| birthday | datetime | YES | | NULL | |
| score | double | YES | | NULL | |
| info | text | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
c. 插入几条数据
mysql> insert into test values(20131026,'Marry','1983-10-18 21:11:13',65.5,'she
is so nice');
2. 下载mysql jdbc connector
http://dev.mysql.com/downloads/connector/j/
3.创建相应的类
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.util.Scanner;
public class DBConnection { public static Connection getDBConnection() throws Exception {
try{
Connection con = null;
Scanner input=new Scanner(System.in);
System.out.println("please enter the IP");
String ip=input.next();
if(ip.matches("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}"))
{
System.out.println("Your IP is:\n"+ip);
}
else
{
ip="127.0.0.1";
System.out.println("Invaild IP address use default:\n"+ip);
}
System.out.println("please enter the ODBC port");
int port=input.nextInt();
if(1000<port && port < 50000)
{
System.out.println("your port is :\n"+port);
}
else
{
port=3306;
System.out.println("Invaild port use defalt port:\n"+port);
}
System.out.println("please enter the UserName");
String user=input.next();
System.out.println("please enter the Password");
String password =input.next(); String url="jdbc:mysql://"+ip+":"+port+"/"+"study";
// String url="jdbc:mysql://localhost:3306/study";
System.out.println(url);
String driver ="com.mysql.jdbc.Driver";
Class.forName(driver);
con = DriverManager.getConnection(url,"root", "3edc4rfv");
DatabaseMetaData dma = con.getMetaData();//get the database info
System.out.println("Connected to:" + dma.getURL());
System.out.println("Driver " + dma.getDriverName()); return con;
}
catch (Exception e) { System.out.println("[Error] Connection refused: connect");
e.printStackTrace();
return null;
} } }
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Vector;
public class mysql { static void runquery() throws SQLException
{
Connection con=null ; long start=System.currentTimeMillis(); //count runtime
ResultSetMetaData resultMetaData;
try{ con = DBConnection.getDBConnection();
if(con==null){
System.out.println("can't open DBConnection");
}
con.setAutoCommit(false); System.out.println("enter the sql you want excute\n eg select * from test;");
Statement stmt = con.createStatement();
String sql=new Scanner(System.in).nextLine();
ResultSet rs =stmt.executeQuery(sql);
resultMetaData=rs.getMetaData();
int cols = resultMetaData.getColumnCount(); //get the count of all the coulums ,this will be 5
Vector currentRow = new Vector();
while(rs.next())
{
for (int j = 1; j < cols; j++) {
switch (resultMetaData.getColumnType(j)) //translate the column of table type to java type then write to vector
{
case Types.VARCHAR:
currentRow.addElement(rs.getString(resultMetaData.getColumnName(j)));
break;
case Types.INTEGER:
currentRow.addElement(new Integer(rs.getInt(resultMetaData.getColumnName(j))));
break;
case Types.TIMESTAMP:
currentRow.addElement(rs.getDate(resultMetaData.getColumnName(j)));
break;
case Types.DOUBLE:
currentRow.addElement(rs.getDouble(resultMetaData.getColumnName(j)));
break;
case Types.FLOAT:
currentRow.addElement(rs.getFloat(resultMetaData.getColumnName(j)));
break;
case Types.CLOB:
currentRow.addElement(rs.getBlob(resultMetaData.getColumnName(j)));
break;
default:
currentRow.add("error");
} } System.out.println(currentRow);
currentRow.clear(); } }
catch (Exception e) { e.printStackTrace();
} con.close(); long end=System.currentTimeMillis(); System.out.println(end-start); }
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
System.out.println("enter the query SQL you want run\nex. select * from test ") ;
runquery();
}
运行结果:
ex. select * from test
please enter the IP
localhost
Invaild IP address use default:
127.0.0.1
please enter the ODBC port
3306
your port is :
3306
please enter the UserName
root
please enter the Password
3edc4rfv
jdbc:mysql://127.0.0.1:3306/study
Connected to:jdbc:mysql://127.0.0.1:3306/study
Driver MySQL Connector Java
enter the sql you want excute
eg select * from test;
select * from test;
[20131024, Jason, 1980-05-07, 60.5]
[20131025, Young, 1988-01-09, 56.8]
[20131026, Marry, 1983-10-18, 65.5]
31977
enter the instert SQL you want run
不知道数据库中表的列类型的前提下,使用JDBC正确的取出数据的更多相关文章
- mybatis框架下解决数据库中表的列的字段名和实体类属性不相同的问题
导包.... 实体类中的属性,getter,setter,tostring,构造等方法就不写了 private int id; private String orderNo; private floa ...
- thinkphp怎么把数据库中的列的值存到下拉框中
1. 先去数据库中查值,查询整个数据表,结果为二维数组. $project = M("project"); $cell = $project->where(array('st ...
- Mysql 数据库 表中列的操作
[1]Mysql数据库中表的列操作 Mysql中关于表中列的操作集语句: -- [1]增加一列 ) DEFAULT NULL COMMENT '目的码区号'; -- [2]增加一列,在dnis_are ...
- 报错:无效的列类型: 1111;must be specified for all nullable parameters.
org.springframework.jdbc.UncategorizedSQLException: Error setting null parameter. Most JDBC drivers ...
- MySql学习 (一) —— 基本数据库操作语句、三大列类型
注:该MySql系列博客仅为个人学习笔记. 在使用MySql的时候,基本都是用图形化工具,如navicat.最近发现连最基本的创建表的语法都快忘了... 所以,想要重新系统性的学习下MySql,为后面 ...
- 数据库-SQL语句:删除和修改语句-列类型-列约束
使用MySQL客户端连接服务器的两种方式: (1)交互模式: ——查 mysql.exe -h127.0.0.1 -uroot -p mysql -uroot (2)脚本模式:——增删改 m ...
- sql server 修改列类型
如下代码中为修改bcp数据库中表B_TaskFileMonitor中的列FileSizeOriginal的类型为bigint use bcp; ); --判断是否存在这一列 IF COL_LENGTH ...
- 数据库中表的复杂查询&分页
一.数据库中表的复杂查询 1)连接查询 1.0连接的基本的语法格式: from TABLE1 join_type TABLE2 [on (join_condition)][where (query_c ...
- 操作MyBatis引发Error setting null for parameter #X with JdbcType OTHER .无效的列类型
再用MyBatis操作Oracle的时候,传入null值而引发的错误 异常信息: org.springframework.jdbc.UncategorizedSQLException: Error s ...
随机推荐
- [Angularjs]表单验证
写在前面 在开发中提交表单,并对表单的值进行验证是非常常见的操作,angularjs对表单验证提供了非常好的支持. demo 表单 <form name="myform" n ...
- ThinkPHP3.2对接开发支付宝即时到帐接口
ThinkPHP3.2对接开发支付宝即时到帐接口 在做一些商城.自动发卡网站.会员积分充值.金币充值等等这类网站都时候,我们极大可能需要使用到第三方都支付接口.不管是财付通.支付宝.银联.贝宝.易宝这 ...
- Myeclipse右键新建项目突然变的很少
额,很是焦躁,最后在界面的右上方点Myeclipse Java enterprise变回原来模样
- HTML5音乐播放器(最新升级改造加强版)
最近么,单位里面么老不顺心的,公司一直催要程序员要PHP,然后本宅好不容易推荐了一个,我日嘞,最后待遇变成1.3,吾师最后也同意1.3W,然后还说要考虑... 尼玛,4年多5年不到一点的工作经验,前端 ...
- 更改vs自带的模板
路径:C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTemplatesCache\CSharp\Code\20 ...
- SQL Server2005主从复制实现
转自:http://blog.csdn.net/gaojier1000/article/details/5805814 一. 准备工作:1 .在发布服务器上建立一个共享目录,作为发布快照文件的 ...
- [译]angularjs directive design made easy
原文: http://seanhess.github.io/2013/10/14/angularjs-directive-design.html AngularJS directives很酷 Angu ...
- [译]Probable C# 6.0 features illustrated
原文: http://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated ========================= ...
- 分分钟教会大家第一个Spring入门案例
1.下载Spring jar包,并添加到项目中. 官网地址http:springsource.org 2.在项目中新建一个类 package cn.test; public class He ...
- Sql统计一个字符串在另一个字符串出现的次数的函数-fnQueryCharCountFromString
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ),)) returns int as begin declare @pos int,@n int , ...