开发者

SQLite and Java

When I create a new project in Netbeans, I added the sqlite.jar to the classpath and library. I wrote a short test program and it works great!

Now I want to add a GUI as a front end, so I create a brand new project in Netbeans but I create a swing project and create the GUI using netbeans. The GUI works fine by itself (just taking input and writing it to the console as a test).

So now in the GUI project I go and in the "Source Package" folder I add a new java class and I copy/paste the code from my other (working) sqlite implementation. I also add sqlite to the Classpath/library and nothing works!

This is (part) of the code I have:

package my.test;

import java.sql.*;

public class sqlaccess {
    Class.forName ("org.sqlite.JDBC");
    Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
    Statement stat = conn.createStatement();
    /* commented out the connecting/creating tables etc code */
}

The error I get is this:

C:\Users\xxx\Documents\NetBeansProjects\TestUser\src\my\testuser\sqlaccess.java:12:    <identifier> expected
Class.forName ("org.sqlite.JDBC");
C:\Users\xxx\Documents\NetBeansProjects\TestUser\src\my\testuser\sqlaccess.java:12: illegal start of type
Class.forName ("org.sqlite.JDBC");

So I'm pretty sure the problem is the way I combine these 2 classes/files since each one work开发者_运维问答s perfect stand alone.


The problem is this code block:

Class.forName ("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
Statement stat = conn.createStatement();

You need to move this code into a method, a constructor, a static initializer, or something similar. Code cannot be placed directly into the class body in Java.


How about ..

public class sqlaccess {
  void init(){
    try{
      Class.forName ("org.sqlite.JDBC");
      Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
       Statement stat = conn.createStatement();
      /* commented out the connecting/creating tables etc code */
    }
    catch(ClassNotFoundException ex){
       //Handle Exception
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜