无法从eclipse连接到sqlite?

时间:2016-07-04 15:12:05

标签: java database eclipse sqlite

大家好,所以我有这个简单的java要做,我正在尝试从eclipse连接到一个sqlite数据库,但它根本不起作用。

这是我的代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class DatabaseConnection {

    private String pathDB="C:\\sqlite\\test.db";
    private Connection connection=null;
    private Statement statement=null;


    public DatabaseConnection(String path){
    pathDB= path;


   }

public void connect () {
    try {
        Class.forName("org.sqlite.JDBC");
        connection= DriverManager.getConnection("jdbc:sqlite:" + pathDB);
        statement= connection.createStatement();
        System.out.println("Connection to " + pathDB + " "+ "successful");

    } catch (ClassNotFoundException notFoundException) {
        notFoundException.printStackTrace();
        System.out.println("Connection Error!");

    } catch (SQLException sqlException) {

        sqlException.printStackTrace();
        System.out.println("Connection Error!");
    }

    String query="Insert into Identity values(0,'issam','issam@mail.com')";
    try {
        statement.executeUpdate(query);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    }

public void close() {
    try {
        connection.close();
        statement.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    }
}

主要课程:

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DatabaseConnection connection= new DatabaseConnection("test.db");
        connection.connect();
        connection.close();



    }

}

所以我有这个sqlite数据库,但每当我运行代码时它总是给我:连接到"路径"无论我走的是什么道路都很成功......

我想我已经完成了所有事情,我下载了sqlite JDBC文件并添加了它: enter image description here

我尝试在数据库表中添加一个新行,但它总是给我这个:

Connection to test.db successful
java.sql.SQLException: no such table: Identity
    at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
    at org.sqlite.core.NativeDB._exec(Native Method)
    at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
    at com.issam.iamcore.DatabaseConnection.connect(DatabaseConnection.java:41)
    at com.issam.iamcore.Main.main(Main.java:10)
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database   (Connection is closed)
    at org.sqlite.core.DB.newSQLException(DB.java:890)
    at org.sqlite.core.CoreStatement.internalClose(CoreStatement.java:109)
    at org.sqlite.jdbc3.JDBC3Statement.close(JDBC3Statement.java:35)
    at com.issam.iamcore.DatabaseConnection.close(DatabaseConnection.java:63)
    at com.issam.iamcore.Main.main(Main.java:11)

任何帮助都会得到解决,谢谢!

1 个答案:

答案 0 :(得分:0)

您已成功连接到数据库,但在执行插入查询之前未创建表Identity,如堆栈跟踪中所述:

Connection to test.db successful
java.sql.SQLException: no such table: Identity

在插入行之前调用它:

String createQuery = "CREATE TABLE Identity (id INT PRIMARY KEY NOT NULL, name TEXT, email TEXT)";
statement.executeUpdate(createQuery);