简体   繁体   English

需要帮助将awt应用程序与MS Access数据库连接

[英]Need help to connect the awt app with MS Access database

I have developed an awt program and now i am trying to connect it to the MS Access Database using ODBC bridge. 我已经开发了awt程序,现在我正尝试使用ODBC桥将其连接到MS Access数据库。

Here is the code :- 这是代码:-

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);
}
}

When i use the following statement in the actionListener 当我在actionListener中使用以下语句时

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

the values are inserted into the database.But when i use the statement,which now takes values from the textfield, 值插入数据库。但是当我使用语句时,现在从文本字段中获取值,

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

as used in the above code,i am getting the exception ,which i catch using the try catch block. 如以上代码中所使用的,我正在获取异常,我使用try catch块捕获了该异常。

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

There is definitely something wrong in the sql statement .Where am i wrong??? sql语句中肯定有问题。我在哪里错???

检查值s1里面的内容,它必须不是有效的String才能解析为int

wrap your s2 inside inside single quotes('') as you were doing in your first insert statement. 就像在第一个insert语句中一样,将s2包装在单引号('')内。

try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM