我正在使用MS Access 2007并尝试插入数据并且我得到异常并且我已经通过使用[]括号尝试了它但它无法正常工作。它成功创建了DBF文件但没有生成确切的输出。
import java.sql.*;
public class Test
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dataSourceName = "mdbTEST";
String dbURL = "jdbc:odbc:" + dataSourceName;
Connection con = DriverManager.getConnection(dbURL, "","");
// creating a java.sql.Statement so I can run queries
Statement s = con.createStatement();
s.execute("create table TESTME ( olumn_name integer )");
// creating a table
// inserting some data into the table
s.execute("insert into TESTME values(3)");
// selecting the data from the table
s.execute("[select column_name from TESTME]");
//getting any ResultSet that came from our query
ResultSet rs = s.getResultSet();
if (rs != null)
// if rs == null, then there is no ResultSet to view
while ( rs.next() )
{
/* the next line will get the first column in our current row's ResultSet
as a String ( getString( columnNumber) ) and output it to the screen */
System.out.println("[Data from column_name:]" + rs.getString(1) );
}
s.execute("drop table TESTME");
s.close();
con.close();
}
catch (Exception err)
{
System.out.println("ERROR: " + err);
}
}
}
答案 0 :(得分:1)
您的陈述
s.execute("[select column_name from TESTME]");
将无效,因为Access SQL使用方括号来分隔表和列名称,因此您的SQL“查询”包含一个没有SELECT
关键字的单个名称。我建议......
s.execute("SELECT [column_name] FROM [TESTME]");
...但由于CREATE TABLE
声明中的拼写错误,这可能无效。试试这个:
s.execute("SELECT [olumn_name] FROM [TESTME]");
以下代码适用于我:
import java.sql.*;
public class JDBCQuery {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\Public\\Database1.accdb;");
Statement s = conn.createStatement();
s.execute("CREATE TABLE [TESTME] ([column_name] integer)");
s.execute("INSERT INTO [TESTME] VALUES (3)");
s.execute("SELECT [column_name] FROM [TESTME]");
ResultSet rs = s.getResultSet();
if (rs!=null)
{
while (rs.next())
{
System.out.println("Data from column_name: " + rs.getString(1));
}
}
s.execute("DROP TABLE [TESTME]");
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
(请注意,运行此代码时,数据库文件Database1.accdb
已存在。)