2012-11-04 58 views
0

我开发了一个awt程序,现在我试图使用ODBC桥将它连接到MS Access数据库。需要帮助将awt应用程序连接到MS Access数据库

下面是代码: -

import java.awt.*; 
import java.awt.event.*; 
import java.awt.GridLayout; 
import java.sql.DriverManager; 
import java.sql.Connection; 
import java.sql.SQLException; 
import java.sql.*; 

class MyClass 
{ 
    public static void main(String args[]) 
    { 
    Project prj=new Project(); 
    } 
} 

class Project 
{ 
Statement s; 
Connection con; 
String s1,s2; 
TextField t1,t2; 
Button b1,b2; 

Project() 
{ 
Frame f=new Frame("Registration"); 
f.setLayout(new GridLayout(2,1)); 
f.setSize(400,400); 

Panel p1=new Panel(); 
p1.setLayout(new FlowLayout()); 
t1=new TextField(15); 
t2=new TextField(30); 
p1.add(new Label("Roll :")); 
p1.add(t1); 
p1.add(new Label("Name :")); 
p1.add(t2); 
f.add(p1); 

Panel p2=new Panel(); 
p2.setLayout(new FlowLayout()); 
s1=t1.getText(); 
s2=t2.getText(); 

try{ 
    try 
     {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
     } 
     catch(Exception e){} 
    con=DriverManager.getConnection("jdbc:odbc:testdb"); 
    s=con.createStatement(); 
    }catch(SQLException e){System.out.println("Error in connecting to database"); } 

b1=new Button("Submit"); 
b1.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent e){ 
    try{ 
s.executeUpdate("insert into college(Roll,Names) values("+Integer.parseInt(s1)+","+s2+")");   
    }catch(SQLException se){ 
    System.out.println(se);} 
}}); 
b2=new Button("Quit"); 
b2.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent e){System.exit(0); 
    }}); 
p2.add(b1); 
p2.add(b2); 
f.add(p2); 
f.pack(); 

    f.setVisible(true); 
} 
} 

当我用下面的语句在

s.executeUpdate("insert into college(Roll,Names) values (555,'Naveen')"); 

值插入database.But的的ActionListener当我使用的说法,现在从文本字段中取值,

s.executeUpdate("insert into college(Roll,Names) values ("+Integer.parseInt(s1)+","+s2+")"); 

在上面的代码中,我得到这个例外,我使用了try catch块。

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1. 

sql语句肯定有什么问题。我在哪里错了?

+0

您的S1没有在此行有效的int的Integer.parseInt(S1),从而NFE .. – PermGenError

+0

@ chaitanya10:S1包含作为通过从文本字段中获得的整数值字符串,所以我用Integer.parseInt(s1)将该字符串值转换回int.What是问题? –

+0

尝试打印一次字符串 – PermGenError

回答

0

包裹内单引号(“”)里面的S2作为你在你的第一个插入语句做。

尝试:

s.executeUpdate("insert into college(Roll,Names) values ("+Integer.parseInt(s1)+",'"+s2+"')"); 
+0

:宾果,它的工作! –

+0

欢迎您:) – PermGenError

1

检查什么里面S1传来的值,它必须是无效的字符串来分析转换成int