I have developed an awt program and now i am trying to connect it to the MS Access Database using ODBC bridge.
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
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.
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???
wrap your s2 inside inside single quotes(”) as you were doing in your first insert statement.
try this: