the last days I was trying to learn how to access mySQL databases via Java.
I am able to load the driver and get a connection to the database ( at least I think so, since I don't get an exception there..)
the code is:
import java.sql.*;
public class test
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded...");
}
catch(ClassNotFoundException e){
System.out.println("Error in loading the driver..."+e);
System.exit(0);
}
try
{
Connection dbConnection= DriverManager.getConnection("jdbc:odbc:test","root","password");
System.out.println("Connection successful...");
Statement stmt = dbConntection.createStatement();
stmt.executeUpdate("create table Accounts ( name char(20) )");
}
catch(SQLException e)
{
System.out.println("database-ConnectionError: "+e);
System.exit(0);
}
}
}
When I execute it, it says:
driver loaded...
Connection successful...
database-ConnectionError: java.sql.SQLException: [MySQL][ODBC 5.2(w) Driver][mysqld-5.5.31]No database selected
I really don't know the problem, because I thought the database is selected during the "getConnection" process....
I tried to select a database by adding this line:
stmt.executeUpdate("use test;");
after creating the Statement.
unfortunately it didn't work because I got another exception which said I should check on the syntax. I don't understand that either because in my commandline it works just fine...
I don't know if it is possible to use these type of commands via Java so if it isn't, please forgive my mistake.
I hope you can help me and I didn't miss the solution during my own search!
Already Thanks to all who reply and use their time on my problems!
ps. If I forgot to point out some important infos ( I don't think i did) please ask:)
edit: I also tried to create a new database during runtime
stmt.executeUpdate("CREATE DATABASE test;");
this actually works, but the database won't be selected either...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…