这段代码,哪里错了???

zxy_cp 2002-09-21 01:38:38
package database;


import java.net.URL;
import java.sql.*;
import java.util.*;

public class testdatabase {
ResultSet results;
ResultSetMetaData rsmd;
DatabaseMetaData dma;
Connection con;
int numcols,i;

public testdatabase() throws Exception {
String sUrl="jdbc:microsoft:sqlserver://"+"192.168.16.1:1433;"+"databasename=user";
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con=DriverManager.getConnection(sUrl,"sa","");
dma=con.getMetaData();
System.out.println("Connected to:"+dma.getURL());
System.out.println("Driver:"+dma.getDriverName());
String types[]=new String[1];
types[0]="TABLES";
results=dma.getTables(null,null,"%",types);
try{
printResult("-------Tables-------");
}
catch(Exception e){e.printStackTrace();}
results.close();
}
protected void printResult(String s) throws Exception{
System.out.println(s);
rsmd=results.getMetaData();
numcols=rsmd.getColumnCount();
for(i=1;i<=numcols;i++)
System.out.print(rsmd.getColumnName(i)+" ");
System.out.println();
while(results.next()){
for(i=1;i<=numcols;i++)
System.out.print(results.getString(i)+" ");
System.out.println();
}
}


public static void main(String[] args) {
try{
testdatabase mydatabase=new testdatabase();
}
catch (Exception e){e.printStackTrace();}
}
}

输出结果如下:
Connected to:jdbc:microsoft:sqlserver://192.168.16.1:1433;SELECTMETHOD=direct;DATABASENAME=user;LOGINTIMEOUT=0

Driver:SQLServer

-------Tables-------

TABLE_CAT TABLE_SCHEM TABLE_NAME TABLE_TYPE REMARKS


结果没有输出我连接的数据库里的所有表的信息,发现results里没有数据。
该怎么做,我才能得到所有表的信息呢???
...全文
44 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
mysine 2002-09-21
  • 打赏
  • 举报
回复
// Each time through this loop, check to see if there were any
// warnings. Note that there can be a whole chain of warnings.
finally { // print out any warnings that occurred
SQLWarning w;
for(w=conn.getWarnings(); w != null; w=w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() +
":" + w.getSQLState());
}
}
}
// Handle exceptions that occur during argument parsing, database
// connection setup, etc. For SQLExceptions, print the details.
catch (Exception e) {
System.err.println(e);
if (e instanceof SQLException)
System.err.println("SQL State: " +
((SQLException)e).getSQLState());
System.err.println("Usage: java ExecuteSQL [-d <driver>] " +
"[-u <user>] [-p <password>] <database URL>");
}

// Be sure to always close the database connection when we exit,
// whether we exit because the user types 'quit' or because of an
// exception thrown while setting things up. Closing this connection
// also implicitly closes any open statements and result sets
// associated with it.
finally {
try { conn.close(); } catch (Exception e) {}
}
}

/**
* This method attempts to output the contents of a ResultSet in a
* textual table. It relies on the ResultSetMetaData class, but a fair
* bit of the code is simple string manipulation.
**/
static void printResultsTable(ResultSet rs, OutputStream output)
throws SQLException
{
// Set up the output stream
PrintWriter out = new PrintWriter(output);

// Get some "meta data" (column names, etc.) about the results
ResultSetMetaData metadata = rs.getMetaData();

// Variables to hold important data about the table to be displayed
int numcols = metadata.getColumnCount(); // how many columns
String[] labels = new String[numcols]; // the column labels
int[] colwidths = new int[numcols]; // the width of each
int[] colpos = new int[numcols]; // start position of each
int linewidth; // total width of table

// Figure out how wide the columns are, where each one begins,
// how wide each row of the table will be, etc.
linewidth = 1; // for the initial '|'.
for(int i = 0; i < numcols; i++) { // for each column
colpos[i] = linewidth; // save its position
labels[i] = metadata.getColumnLabel(i+1); // get its label
// Get the column width. If the db doesn't report one, guess
// 30 characters. Then check the length of the label, and use
// it if it is larger than the column width
int size = metadata.getColumnDisplaySize(i+1);
if (size == -1) size = 30; // Some drivers return -1...
if (size > 500) size = 30; // Don't allow unreasonable sizes
int labelsize = labels[i].length();
if (labelsize > size) size = labelsize;
colwidths[i] = size + 1; // save the column the size
linewidth += colwidths[i] + 2; // increment total size
}

mysine 2002-09-21
  • 打赏
  • 举报
回复
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));

// Loop forever, reading the user's queries and executing them
while(true) {
System.out.print("sql> "); // prompt the user
System.out.flush(); // make the prompt appear now.
String sql = in.readLine(); // get a line of input from user

// Quit when the user types "quit".
if ((sql == null) || sql.equals("quit")) break;

// Ignore blank lines
if (sql.length() == 0) continue;

// Now, execute the user's line of SQL and display results.
try {
// We don't know if this is a query or some kind of
// update, so we use execute() instead of executeQuery()
// or executeUpdate() If the return value is true, it was
// a query, else an update.
boolean status = s.execute(sql);

// Some complex SQL queries can return more than one set
// of results, so loop until there are no more results
do {
if (status) { // it was a query and returns a ResultSet
ResultSet rs = s.getResultSet(); // Get results
printResultsTable(rs, System.out); // Display them
}
else {
// If the SQL command that was executed was some
// kind of update rather than a query, then it
// doesn't return a ResultSet. Instead, we just
// print the number of rows that were affected.
int numUpdates = s.getUpdateCount();
System.out.println("Ok. " + numUpdates +
" rows affected.");
}

// Now go see if there are even more results, and
// continue the results display loop if there are.
status = s.getMoreResults();
} while(status || s.getUpdateCount() != -1);
}
// If a SQLException is thrown, display an error message.
// Note that SQLExceptions can have a general message and a
// DB-specific message returned by getSQLState()
catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage()+ ":" +
e.getSQLState());
}
mysine 2002-09-21
  • 打赏
  • 举报
回复
我这里有通用连接数据库,得到数据库数据的程序供你参考
/**
* A general-purpose SQL interpreter program.
**/
public class ExecuteSQL {
public static void main(String[] args) {
Connection conn = null; // Our JDBC connection to the database server
try {
String driver = null, url = null, user = "", password = "";

// Parse all the command-line arguments
for(int n = 0; n < args.length; n++) {
if (args[n].equals("-d")) driver = args[++n];
else if (args[n].equals("-u")) user = args[++n];
else if (args[n].equals("-p")) password = args[++n];
else if (url == null) url = args[n];
else throw new IllegalArgumentException("Unknown argument.");
}

// The only required argument is the database URL.
for(int n = 0; n < args.length; n++) {
if (args[n].equals("-d")) System.out.println("-d = " + args[++n]);
else if (args[n].equals("-u")) System.out.println("-u = " + args[++n]);
else if (args[n].equals("-p")) System.out.println("-p = " + args[++n]);
else if (url == null) url = args[n];
}

if (url == null)
throw new IllegalArgumentException("No database specified");

// If the user specified the classname for the DB driver, load
// that class dynamically. This gives the driver the opportunity
// to register itself with the DriverManager.
if (driver != null) Class.forName(driver);

// Now open a connection the specified database, using the
// user-specified username and password, if any. The driver
// manager will try all of the DB drivers it knows about to try to
// parse the URL and connect to the DB server.
conn = DriverManager.getConnection(url, user, password);

// Now create the statement object we'll use to talk to the DB
Statement s = conn.createStatement();

// Get a stream to read from the console
1. Java基础部分 7 1、一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制? 8 2、Java有没有goto? 8 3、说说&和&&的区别。 8 4、在JAVA中如何跳出当前的多重嵌套循环? 8 5、switch语句能否作用在byte上,能否作用在long上,能否作用在String上? 9 6、short s1 = 1; s1 = s1 + 1;有什么? short s1 = 1; s1 += 1;有什么? 9 7、char型变量中能不能存贮一个中文汉字?为什么? 9 8、用最有效率的方法算出2乘以8等於几? 10 9、请设计一个一百亿的计算器 10 10、使用final关键字修饰一个变量时,是引用不能变,还是引用的对象不能变? 11 11、"=="和equals方法究竟有什么区别? 12 12、静态变量和实例变量的区别? 13 13、是否可以从一个static方法内部发出对非static方法的调用? 13 14、Integer与int的区别 13 15、Math.round(11.5)等於多少? Math.round(-11.5)等於多少? 14 16、下面的代码有什么不妥之处? 14 17、请说出作用域public,private,protected,以及不写时的区别 14 18、Overload和Override的区别。Overloaded的方法是否可以改变返回值的类型? 15 19、构造器Constructor是否可被override? 16 20、接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承具体类(concrete class)? 抽象类中是否可以有静态的main方法? 16 21、写clone()方法时,通常都有一行代码,是什么? 16 22、面向对象的特征有哪些方面 17 23、java中实现多态的机制是什么? 18 24、abstract class和interface有什么区别? 18 25、abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized? 20 26、什么是内部类?Static Nested Class 和 Inner Class的不同。 20 27、内部类可以引用它的包含类的成员吗?有没有什么限制? 22 28、Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)? 23 29、super.getClass()方法调用 23 30、String是最基本的数据类型吗? 24 31、String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 24 32、是否可以继承String类? 25 33、String s = new String("xyz");创建了几个String Object? 二者之间有什么区别? 25 34、String 和StringBuffer的区别 25 35、如何把一段逗号分割的字符串转换成一个数组? 26 36、数组有没有length()这个方法? String有没有length()这个方法? 26 37、下面这条语句一共创建了多少个对象:String s="a"+"b"+"c"+"d"; 26 38、try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后? 27 39、下面的程序代码输出的结果是多少? 28 40、final, finally, finalize的区别。 30 41、运行时异常与一般异常有何异同? 30 42、error和exception有什么区别? 30 43、Java中的异常处理机制的简单原理和应用。 30 44、请写出你最常见到的5个runtime exception。 31 45、JAVA语言如何进行异常处理,关键字:throws,throw,try,catch,finally分别代表什么意义?在try块中可以抛出异常吗? 32 .... ....

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧