概要: 使用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正确的取出数据的更多相关文章

  1. mybatis框架下解决数据库中表的列的字段名和实体类属性不相同的问题

    导包.... 实体类中的属性,getter,setter,tostring,构造等方法就不写了 private int id; private String orderNo; private floa ...

  2. thinkphp怎么把数据库中的列的值存到下拉框中

    1. 先去数据库中查值,查询整个数据表,结果为二维数组. $project = M("project"); $cell = $project->where(array('st ...

  3. Mysql 数据库 表中列的操作

    [1]Mysql数据库中表的列操作 Mysql中关于表中列的操作集语句: -- [1]增加一列 ) DEFAULT NULL COMMENT '目的码区号'; -- [2]增加一列,在dnis_are ...

  4. 报错:无效的列类型: 1111;must be specified for all nullable parameters.

    org.springframework.jdbc.UncategorizedSQLException: Error setting null parameter. Most JDBC drivers ...

  5. MySql学习 (一) —— 基本数据库操作语句、三大列类型

    注:该MySql系列博客仅为个人学习笔记. 在使用MySql的时候,基本都是用图形化工具,如navicat.最近发现连最基本的创建表的语法都快忘了... 所以,想要重新系统性的学习下MySql,为后面 ...

  6. 数据库-SQL语句:删除和修改语句-列类型-列约束

    使用MySQL客户端连接服务器的两种方式: (1)交互模式: ——查 mysql.exe  -h127.0.0.1  -uroot  -p mysql   -uroot (2)脚本模式:——增删改 m ...

  7. sql server 修改列类型

    如下代码中为修改bcp数据库中表B_TaskFileMonitor中的列FileSizeOriginal的类型为bigint use bcp; ); --判断是否存在这一列 IF COL_LENGTH ...

  8. 数据库中表的复杂查询&amp;分页

    一.数据库中表的复杂查询 1)连接查询 1.0连接的基本的语法格式: from TABLE1 join_type TABLE2 [on (join_condition)][where (query_c ...

  9. 操作MyBatis引发Error setting null for parameter #X with JdbcType OTHER .无效的列类型

    再用MyBatis操作Oracle的时候,传入null值而引发的错误 异常信息: org.springframework.jdbc.UncategorizedSQLException: Error s ...

随机推荐

  1. Devexpress-1 DataGrid控件

    参考资料: 使用XtraGrid自定义列计算 DEV GridControl小结 实现对两列求和后作为新的列

  2. jq实现鼠标移动到 图片上放大,移开图片缩小效果(打算封装成插件)

    先看代码 <script> $(function() { $('div').mouseover(function() { $('img').animate({ opacity: '0.9' ...

  3. vs2010 中无法打开 源文件 "stdafx.h" 未定义标识符 “xxx”

    解决方案: 项目属性->配置属性->C/C++->常规->附加包含目录->$(ProjectDir)

  4. javascript自定义滚动条插件,几行代码的事儿

    在实际项目中,经常由于浏览器自带的滚动条样式太戳,而且在各个浏览器中显示不一样,所以我们不得不去实现自定义的滚动条,今天我就用最少的代码实现了一个自定义滚动条,代码量区区只有几十行,使用起来也非常方便 ...

  5. python爬虫神器PyQuery的使用方法

    你是否觉得 XPath 的用法多少有点晦涩难记呢? 你是否觉得 BeautifulSoup 的语法多少有些悭吝难懂呢? 你是否甚至还在苦苦研究正则表达式却因为少些了一个点而抓狂呢? 你是否已经有了一些 ...

  6. HDU 5687 字典树插入查找删除

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=5687 2016百度之星资格赛C题,直接套用字典树,顺便巩固了一下自己对字典树的理解 #include< ...

  7. iOS开发——UI基础-UIButton、UIImageView、UILabel的选择

    1.UILabel - UILabel的常见属性 @property(nonatomic,copy) NSString *text; 显示的文字 @property(nonatomic,retain) ...

  8. BZOJ4610——[Wf2016]Ceiling Functi

    水题一道,不是很懂为啥没人做... 1.题意:纠正一下..bzoj的题意不是很对...注意不是堆,是不平衡的二叉树,就是非旋转的treap, 另外...插入的时候,小于插在左边..大于等于插在右边 2 ...

  9. 解决mvc部署在IIS上以后出现404错误

    首先:aspnet_regiis -i 如果还不行,更改web.config文件,添加红色的部分 <system.webServer> <modules runAllManagedM ...

  10. [POJ1177]Picture

    [POJ1177]Picture 试题描述 A number of rectangular posters, photographs and other pictures of the same sh ...