概要: 使用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. ES6新特性--多行文本

    由于多行字符串用\n写起来比较费事,所以最新的ES6标准新增了一种多行字符串的表示方法,用` ... `表示: `这是一个 多行 字符串`;

  2. Linux关于添加硬盘的那些事儿:笔记

    添加新硬盘:http://note.youdao.com/share/?id=8cf27602cdce36e1d4160f00e9004b00&type=note 关于添加硬盘的那些事儿:   ...

  3. 采用ETL with RDBMS模式来实现ETL

    目前Teradata数据仓库的ETL作业采用ELT方式, 因为loading太重了, 需要将ETL压力转移到专门的ETL Server上. 对于ETL工具, 市场上已有很成熟的商业/开源工具, 比如I ...

  4. IIS 您要访问的网页有问题,无法显示!

    提示:您要访问的网页有问题,无法显示.HTTP 500 – 内部服务器错误.”的问题解决方案! IIS服务器出现错误的原因很多,请尝试以下操作:1.查看网站属性——文档看看启用默认文档中是否存在:in ...

  5. 如何在R中加载”xlsx”包

    1.下载安装对应系统位数的JDK包(Java SE Development Kit) 2.完成后,安装rJava包-low-level r to Java Interface install.pack ...

  6. 使用LIBSVM工具实现样本分类预测——MatLab

    准备工作: https://www.csie.ntu.edu.tw/~cjlin/libsvm/,下载LIBSVM:(LIBSVM工具相较于MATLAB自带的工具:1).支持多分类及回归(‘-s 0’ ...

  7. DatePicker隐藏年月日

    1.隐藏年 ((ViewGroup) (((ViewGroup) dp.getChildAt(0)).getChildAt(0))) .getChildAt(0).setVisibility(View ...

  8. Ruby中Block, Proc, 和Lambda

    Block Blocks就是存放一些可以被执行的代码的块,通常用do...end 或者 {}表示 例如: [1, 2, 3].each do |num| puts num end [1, 2, 3]. ...

  9. OC第六节—— 继承与类别

    1.继承:    父类和子类的关系.    1.1 生活中的继承        父类           子类           父类              子类                 ...

  10. Mysql InnoDB行锁实现方式

    Mysql InnoDB行锁实现方式 InnoDB行锁是通过给索引上的索引项加锁来实现的,这一点MySQL与Oracle不同,后者是通过在数据块中对相应数据行加锁来实现的.InnoDB这种行锁实现特点 ...