概要: 使用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. Linux基本使用(1)-使用GCC编译C语言程序

  2. thinkphp单入口和多入口的访问方法

    完全是参考thinkphp的官网资料 现在, 基本上都是 用 单入口 的方式来做的! thinkphp可创建多入口和单入口两种模式,本文主要讲解创建方法和两者的区别. TP版本:3.1.3 前端:Ho ...

  3. editplus的配置和使用

    editplus以及其他所有软件的 "页" 是一个什么概念? 所谓 页 : 是指 当前 你看到的 "客户区" client 的区域大小. 如果窗口越小, 那么你 ...

  4. CSS-animations和transitions性能:浏览器到底做了什么?

    CSS animations 和 transitions 的性能:浏览器到底做了什么?(译) 原文地址:http://blogs.adobe.com/webplatform/2014/03/18/cs ...

  5. wtforms 使用

    wtforms是一个表单模板库, 下面以修改密码表单为例简单说明其用法. 我们可以用python代码定义form的基本元素, 比如用户名/邮箱, 并给定各个元素的validation条件. 然后在re ...

  6. ansible的使用技巧

    #查看ansible的帮助 $ ansible -h   #ansible 指定不通的模块执行 $ ansible -i /etc/ansible/hosts  docker -u root -m c ...

  7. Timestamp 使用

    Timestamp是一个长整形的类型 1.使用方法一 Timestamp nowdate1 = new Timestamp(System.currentTimeMillis()); System.ou ...

  8. 中国天气预报数据API收集

      {"weatherinfo":{"city":"北京","cityid":"101010100" ...

  9. SQL server 语句新建用户、对用户授权、删除用户实例

    Grant select on tb to db_user --给db_user用户授权 tb表 查询权限 一.命令操作 USE mydb GO --1. 新建测试用户 --1.1 添加登录用户和密码 ...

  10. Divide Two Integers

    视频讲解  http://v.youku.com/v_show/id_XMTY1MTAyODM3Ng==.html int 范围: Integer.MIN_VALUE => -214748364 ...