I am trying to connect to a database. My friend wrote this code but isn’t working. It is not showing any errors.
The name of the database is testdb and table name is tab. It is in the same folder where the code is.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class dbtest {
public static void main(String[] args){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:testdb");
Statement stat = con.createStatement();
stat.executeQuery("insert into tab values ('test','test','test')");
//stat.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(dbtest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(dbtest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Problem is in your odbc connection
goto ControlPanel->AdministrativeTools->DataSource(ODBC)->System DSN->ADD->SqlServer->
then in the name field give the Source Name.
you have to use this name instead of testdb in your DriverManager.getConnection method.
Because getConnectionMethod take the source name not the database name. so your code is not working.
However after filling the source name fill the server field with your server.Then you will be asked to bind the database for the source connection and set your database name.Hopefully you are done.