概要: 使用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. php分页代码简单实现

    版权声明:本文为博主原创文章,未经博主允许不得转载. 数据库操作类代码:mysqli.func.php <?php // 数据库连接常量 define('DB_HOST', 'localhost ...

  2. socket编程报异常java.io.EOFException

    一个客户端连接服务器的小程序,服务器端可以正常读取客户端发来的数据 但是当客户端关闭时,服务端也关闭了,并且抛出如下的异常: java.io.EOFException at java.io.DataI ...

  3. 网站为什么要做SEO

    网站为什么要做seo,不做seo可以吗?因为seo是获得流量比较稳定.长久的方式,也是自身品牌的最好的方式.我们做的网站必须有用户访问或者被用户知道才有价值和意义,而想被用户所了解的话,必须做网络营销 ...

  4. 清北学堂模拟day4 传球接力

    [问题描述]n 个小朋友在玩传球. 小朋友们用 1 到 n 的正整数编号. 每个小朋友有一个固定的传球对象,第 i 个小朋友在接到球后会将球传给第 ai个小朋友, 并且第 i 个小朋友与第 ai个小朋 ...

  5. tcp/ip协议栈调用关系图

    最近阅读了tcp/ip详解卷2,总结一下整个发送过程和接收过程 sendmsg \/ sendit \/ sosend(这一步将数据从用户空间拷贝到内核空间,并且会在这一步判断发送缓存空间是否充足,是 ...

  6. POJ 1850 Code

    组合数学.... Code Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 7202 Accepted: 3361 Descrip ...

  7. php补充

    PHP 教程 echo 和 print 之间的差异:echo - 能够输出一个以上的字符串print - 只能输出一个字符串,并始终返回 1提示:echo 比 print 稍快,因为它不返回任何值. ...

  8. PHP团队 编码规范 & 代码样式风格规范

    一.基本约定 1.源文件 (1).纯PHP代码源文件只使用 <?php 标签,省略关闭标签 ?> : (2).源文件中PHP代码的编码格式必须是无BOM的UTF-8格式: (3).使用 U ...

  9. hexo问题篇(偶尔抽抽疯)

    hexo安安稳稳的跑了很久,然后 ....让人心碎的hexo问题,华丽丽的摔倒在坑里,只因update了hexo version最是哪一句 hexo server让人欲哭无泪 -问题场景 设备: Ma ...

  10. Java多线程基础知识(四)

    一. Condition 接口 1. Condition接口也提供了类似Object的监视器方法,与Lock配合可以实现等待/通知模式. 但是这两者在使用方式以及功能特性上还是有差别的. 2. 支持多 ...