Insert Problem jdbc odbc
I have problem with my Insertion code. here is my code:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.lang.Class;
import java.util.*;
public class BookForm extends JFrame implements ActionListener
//attributes
private JTextField name, address, ICno;
private JButton cancel, book;
private JLabel lb1,lb2, lb3, lb4;
private Container c;
private Connection con;
private ResultSet rs;
private Statement stmt;
private String looks;
private String Busno, $seatno, $date, pric;
public BookForm(String $Busno, String seatno, String date, String $price)
super("Seat No. "+seatno);
c = getContentPane();
c.setLayout(null);
c.setSize(260,260);
Busno = $Busno;
$seatno = seatno;
$date = date;
pric = $price;
// ********** SET UP GUI **********
try{
looks = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(looks);
SwingUtilities.updateComponentTreeUI(this);
}//end of try
catch(Exception e)
System.out.println("Error in UIManager");
lb1 = new JLabel("Name");
lb1.setSize(60,20);
lb1.setLocation(30,30);
lb2 = new JLabel("Address");
lb2.setSize(60,20);
lb2.setLocation(30,60);
lb3 = new JLabel("IC No.");
lb3.setSize(60,20);
lb3.setLocation(30,90);
lb4 = new JLabel("Seat No. : "+$seatno);
lb4.setSize(100,20);
lb4.setLocation(30,120);
name = new JTextField();
name.setSize(150,20);
name.setLocation(100,30);
address = new JTextField();
address.setSize(150,20);
address.setLocation(100,60);
ICno = new JTextField();
ICno.setSize(150,20);
ICno.setLocation(100,90);
cancel = new JButton("Cancel");
cancel.setSize(70,30);
cancel.setLocation(30,190);
cancel.setMnemonic('L');
book = new JButton("Print & Book");
book.setSize(100,30);
book.setLocation(140,190);
book.setMnemonic('R');
c.add(lb1);
c.add(lb2);
c.add(lb3);
c.add(lb4);
c.add(name);
c.add(address);
c.add(ICno);
c.add(cancel);
c.add(book);
cancel.addActionListener(this);
book.addActionListener(this);
}//end o BookForm()
public void actionPerformed(ActionEvent e)
Object source = e.getSource();
if(source == book)
String nam = name.getText();
String add = address.getText();
String ic = ICno.getText();
String busn = Busno;
String seatn = $seatno;
String dat = $date;
boolean validation = validationFunction();
if(validation == false)
JOptionPane.showMessageDialog(null,"Please Fill the Form Completely");
else{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Bus","","");
stmt=con.createStatement();
stmt.executeUpdate("Insert Into PassengerBooking (Name,Address,ICno,BusNo,SeatNo,Date) VALUES ('"+nam+"' , '"+add+"', '"+ic+"', '"+Busno+"', '"+$seatno+"', '"+$date+"')");
stmt.close();
con.close();
catch(SQLException exc)
exc.printStackTrace();
catch(Exception exc)
exc.printStackTrace();
else if(source == cancel)
this.setVisible(false);
public boolean validationFunction()
boolean check = true;
String nam = name.getText();
String add = address.getText();
String ic = ICno.getText();
if(name.equals(""))
check = false;
else if(add.equals(""))
check = false;
else if(ic.equals(""))
check = false;
return check;
I get syntax error in my Insert query. my database column name is: Name, Address, ICno, BusNo, SeatNo, Date
and I have an auto number (BookNo) for that table as a primary key.
Since I am a student and new in java, I dont know which code I type wrongly..
Please Help me, This my Assignment which to be submited next week.
Message was edited by:
Triagip
Note that there is a return value involved. I suggest you try the following first.
executeUpdate
public int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or
DELETE statement or an SQL statement that returns nothing, such as an
SQL DDL statement.
Parameters:
sql - an SQL INSERT, UPDATE or DELETE statement or an SQL statement
that returns nothing
Returns:
either the row count for INSERT, UPDATE or DELETE statements, or 0 for
SQL statements that return nothing
Throws:
SQLException - if a database access error occurs or the given SQL
statement produces a ResultSet object
try {
int returnValue = 0; // Added
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Step 1 complete");
con = DriverManager.getConnection("jdbc:odbc:Bus","","");
System.out.println("Step 2 complete");
stmt=con.createStatement();
System.out.println("Step 3 complete");
returnValue = stmt.executeUpdate("Insert Into PassengerBooking "
+"(Name,Address,ICno,BusNo,SeatNo,Date) "
+"VALUES ('"+nam+"' , '"+add+"', '"+ic+"', '"+Busno+"', '"+$seatno+"', '"+$date+"')");
System.out.println("Inserted ["+returnValue"+"] rows");
stmt.close();
con.close();
}I absolutely agree with the advise you received in isolating the SQL pblms, by making sure the insert statement works apart from the Java wrapper code.
Similar Messages
-
Ms Access problems with Jdbc Odbc!!!
Hi again people,
Im creating a GUI swing project connecting a database (MsAccess) to a dialog using the bridge driver,
The GUI is coming up but im getting runtime errors and the data does not go to the fields, the dialog and connection are in two files:
import java.awt.*;
import java.awt.event.*;
import java.sql.*; //SQL package for the statements
import javax.swing.*;
class DatabaseMan
public ResultSet m_resultSet; //recordset resulting from SQL query
public ResultSetMetaData m_rsmd; //used to get general info about the columns
private int m_nNumberOfFields; //number of fields in a recordset
private Connection conn;
private Statement stmt;
public DatabaseMan(String strSQLQuery)
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try //establish connection to the database
//try to get connection to the database
conn = DriverManager.getConnection("jdbc:odbc:db1");
//this is not where we update the database so we make it read only
stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
m_resultSet = stmt.executeQuery(strSQLQuery);
catch(SQLException exSQL)
System.err.println("\n\n\t\t ***SQLException has" +
"been caught ***\n\n");
while ( exSQL != null)
System.err.println("\nSQLState : " + exSQL.getSQLState() );
System.err.println("\nMessage : " + exSQL.getMessage() );
System.err.println("\nVendor code : "+ exSQL.getErrorCode() );
System.err.println("\n");
exSQL = exSQL.getNextException();
catch( ClassNotFoundException e)
System.err.print("\n\n\tClassNotFoundException has"
+" been caught");
System.err.println( e.getMessage());
catch( java.lang.Exception ex )
ex.printStackTrace();
public void CloseConnection() //close connection to database
try
conn.close();
stmt.close();
m_resultSet.close(); //release the resources
catch (SQLException exSQL )
System.out.println("SQL Exception: " + exSQL.getMessage());
exSQL.printStackTrace(System.out);
public int getNoFields()
return m_nNumberOfFields;
} //end of DatabaseMan.java
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import DatabaseMan;
import javax.swing.*;
class DBviewer extends JDialog implements ActionListener
//JButtons to create toolbar
private JButton m_buttonFirst;
private JButton m_buttonNext;
private JButton m_buttonPrevious;
private JButton m_buttonLast;
private JButton m_buttonClose;
private JButton m_mainbuttonClose;
//textfields to transfer the data from database
private JTextField m_name;
private JTextField m_age;
private JTextField m_weight;
private JTextField m_professionalism;
private JTextField m_speed;
private JTextField m_acceleration;
private JTextField m_jump;
private JTextField m_stamina;
private JTextField m_bravery;
private JTextField m_fitness;
private JTextField m_experience;
//labels to identify the textfields
private JLabel m_labelname;
private JLabel m_labelage;
private JLabel m_labelweight;
private JLabel m_labelspeed;
private JLabel m_labelacceleration;
private JLabel m_labelprofessionalism;
private JLabel m_labeljump;
private JLabel m_labelstamina;
private JLabel m_labelbravery;
private JLabel m_labelfitness;
private JLabel m_labelexperience;
DatabaseMan m_DatabaseMan;
private String strSQLQuery1;
private String type1 = new String("");
public DBviewer(Frame parent, String caption, boolean bModal, String type)
super(parent,caption,true);
setSize(600,400);
setLocation( new Point(150 , 150 )); //position it pops up on screen.
setResizable(false);
strSQLQuery1 = new String("");
type1 = type;
//SQL query to show the horse database
if(type =="Horse")
strSQLQuery1 ="SELECT *" +
"FROM HORSE";
buildHorseGUI();
if(type =="Jockey")
strSQLQuery1 ="SELECT *" +
"FROM JOCKEY"+
" ORDER BY NAME";
buildJockeyGUI();
if(type =="Course")
strSQLQuery1 ="SELECT *" +
"FROM RACECOURSE"+
" ORDER BY NAME";
buildCourseGUI();
m_DatabaseMan = new DatabaseMan(strSQLQuery1);
/*try
{//reset values with default move up to top later
if(m_DatabaseMan.m_resultSet.first())
transferData(type1);
catch( SQLException exSQL)
System.out.println("SQL Exception: " + exSQL.getMessage());
exSQL.printStackTrace(System.out);
public void buildHorseGUI() //construct the horse GUI
buildDefaultGUI(); //build default buttons and toolbar
m_labelname = new JLabel(" Horse Name:",JLabel.CENTER);
m_labelname.setBackground(Color.blue);
m_labelname.setForeground(Color.white);
m_labelage = new JLabel("Age: ",JLabel.CENTER);
m_labelage.setBackground(Color.blue);
m_labelage.setForeground(Color.white);
m_labelweight = new JLabel("Weight(p): ",JLabel.CENTER);
m_labelweight.setBackground(Color.blue);
m_labelweight.setForeground(Color.white);
m_labelspeed = new JLabel("Speed:",JLabel.CENTER);
m_labelspeed.setBackground(Color.blue);
m_labelspeed.setForeground(Color.white);
m_labelacceleration = new JLabel("Acceleration:",JLabel.CENTER);
m_labelacceleration.setBackground(Color.blue);
m_labelacceleration.setForeground(Color.white);
m_labelprofessionalism = new JLabel("Professionalism:",JLabel.CENTER);
m_labelprofessionalism.setBackground(Color.blue);
m_labelprofessionalism.setForeground(Color.white);
m_labeljump = new JLabel("Jump:",JLabel.CENTER);
m_labeljump.setBackground(Color.blue);
m_labeljump.setForeground(Color.white);
m_labelstamina = new JLabel("Stamina:",JLabel.CENTER);
m_labelstamina.setBackground(Color.blue);
m_labelstamina.setForeground(Color.white);
m_labelbravery = new JLabel("Bravery:",JLabel.CENTER);
m_labelbravery.setBackground(Color.blue);
m_labelbravery.setForeground(Color.white);
m_labelfitness = new JLabel("Fitness:",JLabel.CENTER);
m_labelfitness.setBackground(Color.blue);
m_labelfitness.setForeground(Color.white);
m_labelexperience = new JLabel("Experience",JLabel.CENTER);
m_labelexperience.setBackground(Color.blue);
m_labelexperience.setForeground(Color.white);
//creation of textfields to hold the data
//making them non-editable and b/ground of black with white text
m_name = new JTextField(20);
m_name.setEditable(false);
m_name.setBackground(Color.black);
m_name.setForeground(Color.white);
m_age = new JTextField(2);
m_age.setEditable(false);
m_age.setBackground(Color.black);
m_age.setForeground(Color.white);
m_weight = new JTextField(3);
m_weight.setEditable(false);
m_weight.setBackground(Color.black);
m_weight.setForeground(Color.white);
m_speed = new JTextField(2);
m_speed.setEditable(false);
m_speed.setBackground(Color.black);
m_speed.setForeground(Color.white);
m_acceleration = new JTextField(2);
m_acceleration.setEditable(false);
m_acceleration.setBackground(Color.black);
m_acceleration.setForeground(Color.white);
m_professionalism = new JTextField(2);
m_professionalism.setEditable(false);
m_professionalism.setBackground(Color.black);
m_professionalism.setForeground(Color.white);
m_jump = new JTextField(2);
m_jump.setEditable(false);
m_jump.setBackground(Color.black);
m_jump.setForeground(Color.white);
m_stamina = new JTextField(2);
m_stamina.setEditable(false);
m_stamina.setBackground(Color.black);
m_stamina.setForeground(Color.white);
m_bravery = new JTextField(2);
m_bravery.setEditable(false);
m_bravery.setBackground(Color.black);
m_bravery.setForeground(Color.white);
m_fitness = new JTextField(2);
m_fitness.setEditable(false);
m_fitness.setBackground(Color.black);
m_fitness.setForeground(Color.white);
m_experience = new JTextField(2);
m_experience.setEditable(false);
m_experience.setBackground(Color.black);
m_experience.setForeground(Color.white);
//create a panel to hold this data
Panel data = new Panel();
data.setLayout(new GridLayout(0,4));
data.setBackground(Color.blue);
data.add(m_labelname);
data.add(m_name);
data.add(m_labelage);
data.add(m_age);
data.add(m_labelweight);
data.add(m_weight);
data.add(m_labelspeed);
data.add(m_speed);
data.add(m_labelacceleration);
data.add(m_acceleration);
data.add(m_labelprofessionalism);
data.add(m_professionalism);
data.add(m_labeljump);
data.add(m_jump);
data.add(m_labelstamina);
data.add(m_stamina);
data.add(m_labelbravery);
data.add(m_bravery);
data.add(m_labelfitness);
data.add(m_fitness);
data.add(m_labelexperience);
data.add(m_experience);
getContentPane().add(data, BorderLayout.CENTER);
public void buildDefaultGUI() //construct the default components for GUI
JToolBar wndToolBar = new JToolBar();
wndToolBar.setBackground(Color.green);
wndToolBar.setFloatable(false);
m_buttonFirst = new JButton( new ImageIcon( "graphic/myFirst.gif" ) );
m_buttonPrevious = new JButton(new ImageIcon( "graphic/myPrevious.gif" ) );
m_buttonNext = new JButton(new ImageIcon( "graphic/myNext.gif" ) );
m_buttonLast = new JButton(new ImageIcon( "graphic/myLast.gif" ) );
m_buttonClose = new JButton(new ImageIcon( "graphic/myClose.gif" ) );
m_mainbuttonClose = new JButton("CLOSE");
// implement action listener
m_buttonFirst.addActionListener(this);
m_buttonPrevious.addActionListener(this);
m_buttonNext.addActionListener(this);
m_buttonLast.addActionListener(this);
m_buttonClose.addActionListener(this);
m_mainbuttonClose.addActionListener(this);
//set the tool tips for each of the button
m_buttonFirst.setToolTipText( "Display first record" );
m_buttonPrevious.setToolTipText( "Display previous record" );
m_buttonNext.setToolTipText( "Display next record" );
m_buttonLast.setToolTipText( "Display last record" );
m_buttonClose.setToolTipText( "Close this window and return to game" );
m_mainbuttonClose.setToolTipText( "Close this window and return to game" );
m_mainbuttonClose.setBackground(Color.green);
//add these buttons to the toolbar
wndToolBar.add( m_buttonFirst );
wndToolBar.add( m_buttonPrevious );
wndToolBar.add( m_buttonNext );
wndToolBar.add( m_buttonLast );
wndToolBar.addSeparator(); //separator in the toolbar
wndToolBar.add( m_buttonClose );
getContentPane().add(wndToolBar, BorderLayout.NORTH);
getContentPane().add(m_mainbuttonClose, BorderLayout.SOUTH);
public void buildCourseGUI() //construct the course GUI
buildDefaultGUI();
public void buildJockeyGUI() //construct the jockey GUI
buildDefaultGUI();
public void actionPerformed( ActionEvent evt)
//button first record is pressed
if( evt.getSource() == m_buttonFirst )
try
if( m_DatabaseMan.m_resultSet.first() )
transferData(type1);
catch (SQLException exSQL )
System.err.println( exSQL.toString() );
//button next record is pressed
if( evt.getSource() == m_buttonNext )
try
if(!m_DatabaseMan.m_resultSet.isLast())
if(m_DatabaseMan.m_resultSet.next())
transferData(type1);
catch (SQLException exSQL )
System.err.println( exSQL.toString() );
//previous button is pressed
if( evt.getSource() == m_buttonPrevious )
try
if( !m_DatabaseMan.m_resultSet.first())
if(m_DatabaseMan.m_resultSet.previous())
transferData(type1);
catch (SQLException exSQL )
System.err.println( exSQL.toString() );
//last button is pressed
if( evt.getSource() == m_buttonLast )
try
if(m_DatabaseMan.m_resultSet.last())
transferData(type1);
catch (SQLException exSQL )
System.err.println( exSQL.toString() );
// close button(s) pressed
if( evt.getSource() == m_buttonClose)
setVisible( false );
dispose(); //return the dialog window resources
m_DatabaseMan.CloseConnection();
if( evt.getSource() == m_mainbuttonClose)
setVisible( false );
dispose(); //return the dialog window resources
m_DatabaseMan.CloseConnection();
public void transferData(String type1) throws SQLException //return a String
if(type1 =="Horse")
//transfer horse details
m_name.setText(m_DatabaseMan.m_resultSet.getString("NAME"));
m_professionalism.setText(m_DatabaseMan.m_resultSet.getString("PROFESSIONALISM"));
m_speed.setText(m_DatabaseMan.m_resultSet.getString("SPEED"));
m_stamina.setText(m_DatabaseMan.m_resultSet.getString("STAMINA"));
m_weight.setText(m_DatabaseMan.m_resultSet.getString("WEIGHT"));
m_experience.setText(m_DatabaseMan.m_resultSet.getString("EXPERIENCE"));
m_fitness.setText(m_DatabaseMan.m_resultSet.getString("FITNESS"));
m_jump.setText(m_DatabaseMan.m_resultSet.getString("JUMP"));
m_age.setText(m_DatabaseMan.m_resultSet.getString("AGE"));
m_bravery.setText(m_DatabaseMan.m_resultSet.getString("BRAVERY"));
m_acceleration.setText(m_DatabaseMan.m_resultSet.getString("ACCELERATION"));
if(type1 =="Jockey")
m_name.setText(m_DatabaseMan.m_resultSet.getString("NAME"));
m_age.setText(m_DatabaseMan.m_resultSet.getString("AGE"));
if(type1 =="Course")
//transfer course details not implemented yet
} //end of class DBviewer
I ve set up an odbc driver and the database has data in it but I still get this run time error an no data is transfered to the dialog box
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1525)
at sun.jdbc.odbc.JdbcOdbcResultSet.reWordAsCountQuery(JdbcOdbcResultSet.java:6268)
at sun.jdbc.odbc.JdbcOdbcResultSet.calculateRowCount(JdbcOdbcResultSet.java:6061)
at sun.jdbc.odbc.JdbcOdbcResultSet.initialize(JdbcOdbcResultSet.java:150)
at sun.jdbc.odbc.JdbcOdbcStatement.getResultSet(JdbcOdbcStatement.java:420)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:250)
at DatabaseMan.<init>(DatabaseMan.java:34)
at DBviewer.<init>(DBviewer.java:83)
at MainWindow.actionPerformed(MainWindow.java:266)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1450)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1504)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:378)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:250)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:216)
at java.awt.Component.processMouseEvent(Component.java:3715)
at java.awt.Component.processEvent(Component.java:3544)
at java.awt.Container.processEvent(Container.java:1164)
at java.awt.Component.dispatchEventImpl(Component.java:2593)
at java.awt.Container.dispatchEventImpl(Container.java:1213)
at java.awt.Component.dispatchEvent(Component.java:2497)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2451)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2216)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125)
at java.awt.Container.dispatchEventImpl(Container.java:1200)
at java.awt.Window.dispatchEventImpl(Window.java:914)
at java.awt.Component.dispatchEvent(Component.java:2497)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
Im really stuck!!! any suggestions? thanks in advanceThank you for your response and sorry for the length
of code,
Thats was my first idea that it was asking for
or something I dont have but I checked my database and
I dont have any unusually large data entries (most
between 8-15 letters, the others are numbers) could it
be something wrong with how I've entered the database
in MsAccess, or am i barking up the wrong tree again!
Many thanks
RobI think you've misunderstood me. This has nothing to do with unusually large data entries, but rather the opposite. You are wrongly expecting data that is shorter than you think. When you call rs.getString(i) to retrieve a column value of a field, and you only want the first 5 characters in the column (instead of 10 or whatever the column size is), you would do something similar to the following:
String column_value = rs.getString(1).subtstring(0,5);The above expects a String that is at least 5 characters. Your problem is when your column value returned is less than the specified substring index ( in this case 5 ) it will throw an exception. If you changed your code to this, the error will not occur:
String column_value = rs.getString( 1 ).subtstring( 0, 5);
if ( column_value.length() > 5 )
column_value = column_value.substring( 0, 5 );
}Jamie -
Newbie: Problem with jdbc-odbc and MS SQL server 2005
I'm on win vistax64 with SQLSERVER 2005 and I have set up the odbc source as system dsn using the SQL Native Client driver with SQL authentication and the connectivity test in the end succeeds.
I'm trying to make a simple web app that will connect to the database and perform simple querries. It's a school assignment.
I'm using the jdbc-odbc bridge because it's the simplest way to do it and it's what we were shown in class.
I get the following irritating error:
"Cannot establish a connection to jdbc:odb:sstmdb using sun.jdbc.odbc.JdbcOdbcDriver ([Microsoft][ODBC Driver Manager] Data source name not found and no default driver specifies)".
I'm working with netbeans 5.5.1 and this error is what I get when in the runtime tab I try to connect with the jdbc-odbc. I get a similar error in the logs when I try to run the app on the j2ee server.
This is the java class that establishes the connection.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connector {
private static final String dbUrl="jdbc:odbc:sstmdb";
private static final String user="kimon";
private static final String password="jackohara";
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(dbUrl,user,password);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return conn;
}It has worked perfectly on my school PC with winXP and MSDE2000.
What am I missing?Ok, help came from an other way where I was inquiring about a different problem:
Connectivity works fine by using User DSN instead of System DSN for the ODBC source. -
Problem in building JDBC ODBC connection with my stand alone Project.
Hello Everyone!
I gave the following command in order to create JAR file:
C:\app>jar cvfm MyJar.jar Manifest.txt .
and the Manifest file contains the code: Main - Class: Login
My Manifest File and the .class codes and the JAR file which is created successfully by the above command are in the same folder "app" and then I run the project both at command prompt by the command : C:\app>java -jar MyJar.jar
and by double clicking the JAR file. My project is running successfully but, I am using JDBC - ODBC Driver in my project and I want to let this project run in any other computer system. So, any other user who is unknown to the Driver used and Database used in my project can't be able to run my project if the specified driver is not installed in his machine and also there is a bridge of ODBC Data Source (from control panel-- Administrative Tools-- Data Sources(ODBC) )from which Driver is selected and the Database is specified.
In order to test my application, I had removed the data source name from the Control Panel's Data Sources (ODBC) properties' window. Then I run my project then the following error msg is shown in command prompt:
C:\app>java -jar MyJar.jar
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6879)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7036)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:3028)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:3
23)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:174)
at java.sql.DriverManager.getConnection(DriverManager.java:512)
at java.sql.DriverManager.getConnection(DriverManager.java:193)
at Login.<init>(Login.java:37)
at Login.main(Login.java:364)
Error Trace in getConnection() : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
So, I have a doubt at this point that how a user is able to configure this bridge in order to run my application who is unknown to my project's back-hand? As JRE is essential to run my project so, I have decided to give setup of JRE with my project's CD, may the JDBC - ODBC Driver providing to the user with my application setup solve this problem ?
Please help me to solve my problem.M.V.Asolkar wrote:
Please please help me.Lets presume hypothetically that the jTDS driver won't work with 2000. It might or might not.
However the fact remains that your ODBC driver is not working.
So the first step is to stop trying to run your full application. Instead you create a very simple console application that does nothing but connect to the database.
Problems that usually occur from that would be.
1. The connection string is not correct for MS SQL Server.
2. The connection information for the database is not correct
3. The database (nothing to do with java) is not configured to accept connections. -
Problems with JDBC-ODBC Driver
Hello,
I am trying to access a DSN on my windows with a dedicated DB driver of some company. so i used the JDBC-ODBC connector.
when launching the java code, and debugging the problem i get the following error:
DriverManager.getConnection("jdbc:odbc:priority32;UID=Manager;PWD=keren")
trying driver--className=com.mysql.jdbc.Driver,com.mysql.jdbc.Driver@16caf43--
trying driver--className=sun.jdbc.odbc.JdbcOdbcDriver,sun.jdbc.odbc.JdbcOdbcDriver@66848c--
*Driver.connect (jdbc:odbc:priority32;UID=Manager;PWD=keren)
JDBC to ODBC Bridge: Checking security
No SecurityManager present, assuming trusted application/applet
JDBC to ODBC Bridge 2.0001
Current Date/Time: Tue Aug 12 07:50:37 VET 2008
Loading JdbcOdbc library
Allocating Environment handle (SQLAllocEnv)
hEnv=50338088
Allocating Connection handle (SQLAllocConnect)
hDbc=50338256
Connecting (SQLDriverConnect), hDbc=50338256, szConnStrIn=DSN=priority32;UID=Manager;PWD=keren
*Connection.getMetaData
*DatabaseMetaData.getDriverName
Get connection info string (SQLGetInfo), hDbc=50338256, fInfoType=6, len=300
tabula.dll
*DatabaseMetaData.getDriverVersion
Get connection info string (SQLGetInfo), hDbc=50338256, fInfoType=7, len=300
07.00.0000
*DatabaseMetaData.getDriverName
Get connection info string (SQLGetInfo), hDbc=50338256, fInfoType=6, len=300
tabula.dll
Driver name: JDBC-ODBC Bridge (tabula.dll)
*DatabaseMetaData.getDriverVersion
Get connection info string (SQLGetInfo), hDbc=50338256, fInfoType=7, len=300
07.00.0000
Driver version: 2.0001 (07.00.0000)
Caching SQL type information
*Connection.getMetaData
*DatabaseMetaData.getTypeInfo
Allocating Statement Handle (SQLAllocStmt), hDbc=50338256
hStmt=50339424
Get type info (SQLGetTypeInfo), hStmt=50339424, fSqlType=0
Number of result columns (SQLNumResultCols), hStmt=50339424
value=15
Get connection info string (SQLGetInfo), hDbc=50338256, fInfoType=10, len=300
03.52.0000
Fetching (SQLFetch), hStmt=50339424
Column attributes (SQLColAttributes), hStmt=50339424, icol=1, type=2
value (int)=12
Column attributes (SQLColAttributes), hStmt=50339424, icol=1, type=3
value (int)=129
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
CHAR
Get integer data (SQLGetData), hStmt=50339424, column=2
value=12
Get integer data (SQLGetData), hStmt=50339424, column=3
value=0
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
CHAR(1)
Get integer data (SQLGetData), hStmt=50339424, column=2
value=1
Get integer data (SQLGetData), hStmt=50339424, column=3
value=0
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
RCHAR
Get integer data (SQLGetData), hStmt=50339424, column=2
value=12
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
REAL
Get integer data (SQLGetData), hStmt=50339424, column=2
value=6
Get integer data (SQLGetData), hStmt=50339424, column=3
value=0
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
INT
Get integer data (SQLGetData), hStmt=50339424, column=2
value=4
Get integer data (SQLGetData), hStmt=50339424, column=3
value=0
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
UNSIGNED
Get integer data (SQLGetData), hStmt=50339424, column=2
value=4
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
TIME
Get integer data (SQLGetData), hStmt=50339424, column=2
value=10
Get integer data (SQLGetData), hStmt=50339424, column=3
value=0
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
DATE
Get integer data (SQLGetData), hStmt=50339424, column=2
value=11
Get integer data (SQLGetData), hStmt=50339424, column=3
value=0
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
DATE
Get integer data (SQLGetData), hStmt=50339424, column=2
value=9
Get integer data (SQLGetData), hStmt=50339424, column=3
value=0
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
DAY
Get integer data (SQLGetData), hStmt=50339424, column=2
value=4
Fetching (SQLFetch), hStmt=50339424
Get string data (SQLGetData), hStmt=50339424, column=1, maxLen=130
DECIMAL
Get integer data (SQLGetData), hStmt=50339424, column=2
value=3
Get integer data (SQLGetData), hStmt=50339424, column=3
value=0
Fetching (SQLFetch), hStmt=50339424
End of result set (SQL_NO_DATA)
*ResultSet.close
Free statement (SQLFreeStmt), hStmt=50339424, fOption=1
*ResultSet has been closed
Get connection info (SQLGetInfo), hDbc=50338256, fInfoType=44
int value=0
Get connection info (SQLGetInfo), hDbc=50338256, fInfoType=121
RETCODE = -1
ERROR - Generating SQLException...
SQLState(S1096) vendor code(0)
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Information type out of range
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLGetInfo(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.checkBatchUpdateSupport(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at WigsUpdate.main(WigsUpdate.java:25)
getConnection returning driver--className=sun.jdbc.odbc.JdbcOdbcDriver,sun.jdbc.odbc.JdbcOdbcDriver@66848c--what can be done?
thank you very muchHimberJack wrote:
oh now i understand.
i got a very unknown company which supplied the ODBC driver, but they dont have java driver...
so I have nothing to do about it?The choices are find a different driver or use the one you have.
The one you have doesn't do batches.
Finding a different driver could involve the following.
- Buying one from somewhere else
- Pay someone to write one.
- Write a driver yourself.
All of those are somewhat dependent that the "unknown company" has an API that supports that. You (or someone) could also figure out the file format of the "unknown company" as well and then write one. -
Urgent! Problems with bridge JDBC-ODBC
Hello,
I have found out that JDBC-ODBC bridge in JDK 1.4.1 don't works fine, because, if you want to store text largest 254 characters in a field type text in one record of a Access database's table, it generate a SQLError, I have tried with EasySoft JDBC_ODBC and it works, with it I could store text fields largest than 254 characters, but I have new problems, EasySoft bridge is not free, and don't let store nulls in fields type Date [with PreparedStatement x, x.setDate(theDate)] (raise a SQLError), in the other hand, JDKs bridge do it. Somebody knows if exists JDCB-ODBC free drivers more suitables than JDK's includes, or if exists upgrades?
Is very urgent!, Thanks a lot
(Sorry, my english is very poor)I have tried it, Is there where I found the EasySoft's JDBC-ODBC driver, but the result is: one problems out, yes, now with this driver I can store String largest 254 characters in fields type MEMO of a table in Access Database, but two new problems, 1st. is a trial version, (requiere paid), and 2nd. don't let store nulls in fields type Date when JDKs JDBC-ODBC bridge lets, and the aplication needs leave this fields blanks.
Any other idea?
Thank -
OS in my PC is Windows7 Ultimate(64-bit), and I had JDK1.7.0_21(compatible with my PC), Oracle 10G ExpressEdition(32-Bit), ApacheTomcat7.0.11(compatible with my PC).
As my OS is 64-BIT, I accessed C:\Windows\SysWOW64\odbcad32 and I selected UserDSN tab->Add->Microsoft ODBC for Oracle->finish,tapply->ok. Then a Dialog Box appeared and I entered a DSN name=ramsdsn and my DATABASE USERID=rams in username->ok->apply->ok.
But when I tried to compile my program using:
DriverManager.getConnection("jdbc:odbc:ramsdsn","rams","rams");
I got an error:java.sql.SQLException: [Microsoft][ODBC Driver Manager] The specified DSN contains an architecture mismatch between the Driver and Application
Help me FRNZ.. I have been trying it for 7 days and I'm tired of it and I could not figured it yet...
THANKS in Advance...Wrong database is the most likely reason.
Note that the ODBC driver is not a good driver for MS SQL Server. It handles varchar as chars. So an insert of 'A' into a varchar(25) will end up with 'A' followed by 24 spaces. And that probably isn't what you want your varchars to do. -
Problem With Jdbc-Odbc BRidge Connection
I get The following error
SQLException:[Microsoft][ODBC Driver Manager] Invalid cursor state
when using the code
whats the problem with it
import java.sql.*;
public class Employee {
String DBurl;
Connection con;
public Employee(String url)
DBurl=url;
void queryTest()
String query="SELECT * FROM EmpTable";
ResultSet result;
Statement stmt;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(java.lang.ClassNotFoundException e){
System.err.println("Class not Found Exception:");
System.err.println(e.getMessage());
try{
con=DriverManager.getConnection(DBurl,"myLogin","mypassword");
stmt=con.createStatement();
result=stmt.executeQuery(query);
System.out.println("ID"+"\t"+"Name"+"\t"+"Rate"+"\t"+"DeptID");
System.out.println("--"+"\t"+"----"+"\t"+"---"+"\t"+"----");
while(result.next());
String name=result.getString("Name");
int ID=result.getInt("ID");
float rate=result.getFloat("Rate");
int deptID=result.getInt("DeptID");
System.out.println(ID+"\t"+name+"\t"+rate+"\t"+deptID);
stmt.close();
con.close();
catch(SQLException ex){
System.err.println("SQLException:" + ex.getMessage());
public static void main(String args[])
Employee app = new Employee("jdbc:odbc:Employee");
app.queryTest();
}here's your mistake:
while(result.next()); // <--- the loop body is empty.Remove the semi-colon.
% -
I have wrote a JApplet code that using JDBC/ODBC bridge to connecting a local Database (MS Access).
I have used signed applet but it doesn't work and returns the following error message:
java.lang.SecurityException: class "Project1$5"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(ClassLoader.java:522)
at java.lang.ClassLoader.defineClass(ClassLoader.java:485)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:111)
at sun.applet.AppletClassLoader.findClass(AppletClassLoader.java:142)
at java.lang.ClassLoader.loadClass(ClassLoader.java:297)
at sun.applet.AppletClassLoader.loadClass(AppletClassLoader.java:108)
at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:313)
at Project1.showFieldCombo(Project1.java:328)
at Project1.ComboBoxShow(Project1.java:472)
at Project1.init(Project1.java:489)
at sun.applet.AppletPanel.run(AppletPanel.java:344)
at java.lang.Thread.run(Thread.java:484)
Process Exit...
(I have five class file and I have used them in a signed jar file)
What can I do to solving this problem?
Thanks,
PayamI would suggest asking in a different forum since this has nothing to do with JDBC. Perhaps the 'Signed Applets' forum.
-
Problem with locks while using iBATIS with MS Access through JDBC-ODBC brid
Hello,
I am attempting to use iBATIS to access MS Access file via JDBC-ODBC bridge.
(I am using Spring's "SqlMapClientDaoSupport," but that is probably irrelevant)
All this runs on Tomcat... First time DB gets accessed the LDB lock file is created. From there on the only way I can remove the lock file is to kill the JVM...
Any help is greatly appreciated...And why is that a problem?
-
Jdbc:odbc problem with SqlDeveloper
Hi Forum!
My organization is evaluating moving to SQL Developer, the only obstacle for this is that we are running Oracle RDB on a VAX machine, RBD requires a special client driver that is able to work with ODBC, which is what we usually do, I am trying to setup a connection using an ODBC DSN with jdbc:odbc:DSNName, I tested this same JDBC URL with a small java class and it runs just fine, so the problem is that in SQL Developer I get an "Failure: -invalid connection information specified. Verify the URL format for the specified driver".
* Has anyone been successful in configuring an ODBC connection on SQL Developer?
* Any suggestion as to how to connect to Oracle RDB using SQL Developer on Windows XP?
Thanks a lot!
IgnacioHi,
My experience is the following:
- Install Oracle SQL services 7.2 on Alpha machine.
- Configure an OCI (SQLNET) service in SQL services layer.
- Prepare my Rdb database 7.2 to run SQLNET (RDB_NATCONN scripts) and depending on version add users.
- configure the SQLNET layer (TNSNAME) on client side (warning the default VLS listener port is 1527 on VMS instead 1521).
- start SQL Developper and connect Rdb database via TNSNAME. -
Problem: connect DB with Applet by JDBC-ODBC bridge
Dear all,
When I connect local MS SQL server by "sun.jdbc.odbc.JdbcOdbcDriver" as below, it works well! However, when I put the similar code under Java Applet program, it cannot run by showing error:
java.security.AccessControlException: access denied (java.lang.RuntimePermission accessClassInPackage.sun.jdbc.odbc)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
at java.security.AccessController.checkPermission(AccessController.java:399)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
at java.lang.SecurityManager.checkPackageAccess(SecurityManager.java:1501)
at sun.applet.AppletSecurity.checkPackageAccess(AppletSecurity.java:169)
I think Java Applet has some security policy when I try to use applet to connect(read/write) DB. How can I solve it so that I can browse my applet under IE.
Thanks a lot!
Here is my worked code in Java program but not in Applet:
import java.sql.*;
public class TestJDBC1 {
public static void main(String args[]) throws Exception {
String userid = "";
String password = "";
// Register the driver with DriverManager
new sun.jdbc.odbc.JdbcOdbcDriver();
// Get a connection
Connection conn = DriverManager.getConnection("jdbc:odbc:rdr",
userid, password);
// Create a statement for executing SQL
Statement stmt = conn.createStatement();
// Execute a query / SELECT statement
ResultSet rset = stmt.executeQuery("SELECT * FROM PlatformNode");
ResultSetMetaData rsmd = rset.getMetaData();
// Find out how many columns were returned by the query
int count = rsmd.getColumnCount();
// Loop until all rows have been processed
while (rset.next()) {
// Loop until all columns in current row have been processed
for (int i = 1; i <= count; i++) {
// Print out the current value
System.out.print(rset.getObject(i));
// Put a comma between each value
if (i < count) {
System.out.println(",");
// Start the next row's values on a new line
System.out.println("");
// Close the database objects
rset.close();
stmt.close();
conn.close();Hi,
Applets by default are restricted from accessing a lot of things.to enable applest from accessing database and other thngs u need to edit the policy file
Try this.
go to the jre/bin directory open the policytool.exe file
and add permission(in ur case RuntimePermission to access class in package sun.jdbc.odbc) and save the file.
this will enable applets from accessing the databse.
Hope that helps
Note:
policytool.exe must be used to open the java.policy file present in /jre/lib/security directory and then add the permissions
regards,
Partha -
Problem using Jdbc-Odbc Bridge
Hi,
I am using Java 2 SDK and I am trying to access MS Access database on my machine using Jdbc-Odbc bridge. I have set up the DSN in ODBC. But I get the following error when I run my program -
'No Suitable Driver'
Here's my code snippet-
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String dsn = "jdbc:odbc:DriverInfoDB";
Connection con = DriverManager.getConnection(dsn,"","");
con.setAutoCommit(false);
Statement stmt;
String query = null; // SQL select string
ResultSet rs; // SQL query results
stmt = con.createStatement();
.....etc etc...
Where is the error in this code??
Help Needed!!
Thanks
Vivek.try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(dsn,"guest","guest");
OR DriverManager.getConnection(dsn);
System.out.println("Conection's opened");
catch(ClassNotFoundException cnfe)
System.err.println(cnfe);
catch(SQLException sqle)
System.err.println(sqle);
try that code and double check you DSN Name . it's a good practice to greate a system DSN.
i hope that helps.
FEEL FREE TO ASK. WON'T BITE U
ABDUL -
Problem with jdbc:odbc returning incorrect number of rows.
Hello,
Am sure i have done something stupid, but i have an issue with jdbc:odbc ....
It is a simple sceanrio that i have coded umpteen times before ...
I have the following ....
1. Connection to DB2 on an IBM i5 (I apologise for not using native drivers from jt400.jar, but i had an ODBC code example and was in a rush - no excuse i know)
2. Statement object created from connection above
3. A string with my SQL in it
4. A result set for the results.
These are created as follows:
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(ODBCSource, userID, password);
if (con == null) {
// error handling not relevant here
} else {
Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "select * from table";
ResultSet rs = s.executeQuery(SQL);
i then try to loop ....
while (rs.next() )
// stuff
however, i only ever get one result .... if i stick in the check for isLast, the first loop hits this check, i get my little status message, and the loop ends.
while (rs.next() )
if (rs.isLast() )
System.out.println("I am on last record");
BUT if i run the SQL
"select count(*) from table" ... i get a count of 148 !!
I tried setting the FetchSize through setFetchSize(), but made no difference.
This is running on a JBoss server 4.2.1GA, JDK is "jdk1.6.0_02" .... i have a suspicion that this may be a JBoss specfic issue, as this exact code runs just fine on the Domino platform that it was originally on, if this is the case, i apologise for wasting everyones time .... but would still appreciate any pointers you can give me.
CheersHello,
Thanks for the reply, I am not sure i follow what you are saying.
I only mentioned JBoss as it is the application server that we have deployed to and because the orignal code ran fine on a Domino server, I will take your advice and try to run it through in debug rather than running actually on the application server.
Am i incorrect in my assumption that if "select count(*) from table" gives a count of 148, i should expect 148 records in a result set created from "select * from table" ? This is all rather new to me so i apologise if this is incorrect, I'd love to know why this is incorrect so i dont make similar mistakes in future.
Also, If i run this same code on the previous platform, i get 148 iterations of the code contained within
while (rs.next() ) { ... }
When the war file is deployed to JBoss, the same SQL statement gives a result set that only iterates once for
while (rs.next() ) { ... }
The previous platform as I say was domino, but it was running as a lotus notes java agent (despite not using any notes documents etc) as it happened to be where the web pages that call this process were located. It is possible that some of the main code has changed as I had cut and paste the code into a servlet using MyEclipse, but i have double checked the bit that does this SQL request and it is identical
To complete the picture, the new servelt is then called from the action tag on the submit form on a JSP, when it ends the servlet redirects via the requestdispacher to success or failure jsp pages depending on the outcome of the processing.
Thank you again for your help. -
Jdbc-odbc connectivity problem in[b] wsad5.1.2[/b]
while i Try to access the msaccess database using sun.jdbc.odbc.JdbcOdbcDriver,the server is giving the error class not found....sun.jdbc.odbc.JdbcOdbcDriver......
I have already rt.jar containing this class in my jre...
The same thing i tried in wsad5.0 and it is working abs fine....
If anyone has got a time to solve tis query plz help me out...
Its urgent......well,i think nobody has interest in my question.I have asked two questions.
1)Can anybody tell me the compatibilities of JDBC-ODBC bridge versions,oracle and ODBC drivers?
2)And can u tell me how to connect to oracle through a pure Java JDBC drivers (type 4 drivers) on a standalone system?
But u advise me not to use JDBC-ODBC bridge without studying the other part.
Maybe you are looking for
-
Paste ( cmd+v ) not working
For some reason I can not paste into any application anymore using cmd + v on my MacBook running Lion 10.7. Copy ( cmd+c ) seems to work though. So far I have tried repairing permission and setting all keyboard shortcuts to default. Didn´t help. Anyo
-
Hi, It seems to be a common requirement, but nowhere seems to document the solution. We need a multi item view of suppy and demand. At the moment I am looking at combining the logic of BIS views: INVFG_INVENTORY_SUPPLIES and INVFG_INVENTORY_DEMANDS,
-
Hi, i have 10gr2, but need to migrate to 11g. so I installed 11g at another server for testing it. now, what i need to do? i meant import and export complete from the other server!! Help
-
Well my question says it all. I wasn´t using the apple tv, but noticed that the amber light started to blink, so I put it on the tv and there was the apple logo. I did the recory with the "MENU" + "-" button, but came back the same. After a while
-
What kind of monifications or configurations will be effected R3 upgraded
Hi experts, Now we are upgrading our R/3 system to ECC6.0EHP4, there is one common questions which confused me log time. What kind of system monifications or changes will be effected during the ERP( or R/3) upgrade Since normally we know that the mon