无法在asp.net中打开Sqlite数据库

时间:2014-03-01 13:39:32

标签: c# asp.net sqlite

我的项目应显示sqlite3数据库中的数据。数据库名称是db.sqlite3。 错误是:无法打开数据库文件

这是我的代码:

public partial class OverviewAdmin : System.Web.UI.Page
    {

        private SQLiteConnection sql_con;
        private SQLiteCommand sql_cmd;
        private SQLiteDataAdapter DB;
        private DataSet DS = new DataSet();
        private DataTable DT = new DataTable();


        protected void Page_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void SetConnection()
        {
            sql_con = new SQLiteConnection
                ("Data Source=db.sqlite3;");
        }

        private void LoadData()
        {
            SetConnection();
            sql_con.Open();
            sql_cmd = sql_con.CreateCommand();
            string CommandText = "select * from scotty_fahrt";
            DB = new SQLiteDataAdapter(CommandText, sql_con);
            DS.Reset();
            DB.Fill(DS);
            DT = DS.Tables[0];
            GVOutput.DataSource = DT;
            sql_con.Close();
        }

也许是因为数据库文件名。

1 个答案:

答案 0 :(得分:2)

将您的数据库文件放在站点的APP_DATA子文件夹中,并更改将连接设置为

的方法
    private void SetConnection()
    {
        sql_con = new SQLiteConnection
            ("Data Source=|DataDirectory|\\db.sqlite3;");
    }

顺便说一下,我会删除连接的全局变量,并更改SetConnection以返回SQLiteConnection。这将允许应用using语句在异常的情况下正确处理像连接这样的一次性

    private SQLite GetConnection()
    {
        return new SQLiteConnection("Data Source=|DataDirectory|\\db.sqlite3;");
    }

    private void LoadData()
    {
        using(SQLiteConnection cn = GetConnection())
        {
            cn.Open();
            string CommandText = "select * from scotty_fahrt";
            DB = new SQLiteDataAdapter(CommandText, sql_con);
            DS.Reset();
            DB.Fill(DS);
            DT = DS.Tables[0];
            GVOutput.DataSource = DT;
        }
    }