C#和SQLite - 我做错了什么? [英] C# and SQLite - what I do wrong?

查看:68
本文介绍了C#和SQLite - 我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我是程序员初学者,我尝试将SQLite数据库转换为表集(如示例中所示)。我错了什么?我的构造函数不能用正确的表创建对象。

我的班级代码:



公共类bazaDVD 
{
public Klient [] Klienci;
public Film [] Filmy;
public Egzemplarz [] Egzemplarze;
public Wypozyczenie [] Wypozyczenia;


public bazaDVD()
{
DataTable tabelkaK = new DataTable();
DataTable tabelkaF = new DataTable();
DataTable tabelkaE = new DataTable();
DataTable tabelkaW = new DataTable();
SQLiteConnection connect = new SQLiteConnection(Data SOurce = baza_wypozyczalnia.s3db);
SQLiteDataAdapter adapterK = new SQLiteDataAdapter(SELECT * FROM Klienci,connect);
SQLiteDataAdapter adapterF = new SQLiteDataAdapter(SELECT * FROM Filmy,connect);
SQLiteDataAdapter adapterE = new SQLiteDataAdapter(SELECT * FROM Egzemplarze,connect);
SQLiteDataAdapter adapterW = new SQLiteDataAdapter(SELECT * FROM Wypozyczenia,connect);
adapterK.Fill(tabelkaK);
adapterF.Fill(tabelkaF);
adapterE.Fill(tabelkaE);
adapterW.Fill(tabelkaW);
this.Klienci = DataK_TabelaK(tabelkaK);
this.Filmy = DataF_TabelaF(tabelkaF);
this.Egzemplarze = DataE_TabelaE(tabelkaE);
this.Wyp​​ozyczenia = DataW_TabelaW(tabelkaW);

}


私有Klient [] DataK_TabelaK(DataTable tabelaK)
{
for(int i = 0; i< tabelaK。 Rows.Count; i ++)
{
Klienci = new Klient [tabelaK.Rows.Count];
Klienci [i] .KlientId = Convert.ToInt32(tabelaK.Rows [i] [0]);
Klienci [i] .imie = Convert.ToString(tabelaK.Rows [i] [1]);
Klienci [i] .nazwisko = Convert.ToString(tabelaK.Rows [i] [2]);
}
返回Klienci;
}

private Film [] DataF_TabelaF(DataTable tabelaF)
{
for(int i = 0; i< tabelaF.Rows.Count; i ++)
{
Filmy = new Film [tabelaF.Rows.Count];
Filmy [i] .FilmId = Convert.ToInt32(tabelaF.Rows [i] [0]);
Filmy [i] .Rezyser = Convert.ToString(tabelaF.Rows [i] [1]);
Filmy [i] .Tytul = Convert.ToString(tabelaF.Rows [i] [2]);
Filmy [i] .Cena = Convert.ToInt32(tabelaF.Rows [i] [3]);
}
返回Filmy;
}

private Egzemplarz [] DataE_TabelaE(DataTable tabelaE)
{
for(int i = 0; i< tabelaE.Rows.Count; i ++)
{
Egzemplarze = new Egzemplarz [tabelaE.Rows.Count];
Egzemplarze [i] .EgzId = Convert.ToInt32(tabelaE.Rows [i] [0]);
Egzemplarze [i] .FilmId = Convert.ToInt32(tabelaE.Rows [i] [1]);
}
返回Egzemplarze;
}

私人Wypozyczenie [] DataW_TabelaW(DataTable tabelaW)
{
for(int i = 0; i< tabelaW.Rows.Count; i ++)
{
Wypozyczenia = new Wypozyczenie [tabelaW.Rows.Count];
Wypozyczenia [i] .KlientId = Convert.ToInt32(tabelaW.Rows [i] [0]);
Wypozyczenia [i] .EgzId = Convert.ToInt32(tabelaW.Rows [i] [1]);
}
返回Wypozyczenia;
}

}





当我尝试使用时:

 bazaDVD sthnk = new bazaDVD(); 
string elo = Convert.ToString(sthnk.Klienci.Length);
MessageBox.Show(elo);



我得到

类型'System.NullReferenceException'的未处理异常

解决方案

抱歉,您的代码是一场灾难。没关系使用SQLite,你显然不知道如何编码。



你得到一个空引用异常,因为 Klienci 未实例化。它只在这个循环中实例化:

 Klienci =  new  Klient [tabelaK.Rows.Count]; 



所以如果没有行,Klienci将为null。



当然,你实例化的是每一条记录都应该在循环之外进行实例化,所以你永远不会把数据放到数组中。



为什么你想要它在数组中?



这个:

  string  elo = Convert.ToString(sthnk.Klienci.Length); 
MessageBox.Show(elo);



也是一种灾难。您可以这样做:

 MessageBox.Show(sthnk.Klienci.Length.ToString()); 



或:

 MessageBox.Show(String.Format(Length = {0},n)); 





所以,很遗憾地说,问题不在于SQLite,而是你的代码。


你没有显示带有对象引用消息的异常没有设置为对象的实例被抛出。



不用担心。这是检测和修复的最简单的案例之一。它只是意味着某些引用类型的某个成员/变量通过使用和它的实例(非静态)成员解除引用,这要求此成员/变量为非null,但实际上它似乎为null。只需在调试器下执行它,它将停止抛出异常的执行。在该行上设置一个断点,重新启动应用程序并再次到达这一点。评估下一行中涉及的所有引用,并查看哪一个为null,而不需要为null。解决这个问题之后,修复代码:要么确保将成员/变量正确初始化为非空引用,要么将其检查为null,如果为null,则执行其他操作。



另请参阅:想要在按钮点击时显示下一条记录。但是如果下一个记录功能的条件对象引用未设置为对象的实例则会出错。



有时候,你不能这样做在调试器下,由一个或另一个原因。一个非常讨厌的情况是,只有在调试信息不​​可用时构建软件时才会出现问题。在这种情况下,你必须使用更难的方式。首先,你需要确保你永远不会通过静默处理异常来阻止异常的传播(这是开发人员对自己的犯罪,但很常见)。您需要在每个线程的最顶层堆栈帧上捕获绝对所有异常。如果处理类型 System.Exception 的异常,则可以执行此操作。在处理程序中,您需要记录所有异常信息,尤其是 System.Exception.StackTrace

http://msdn.microsoft.com/en-us/library/system.exception.aspx

http://msdn.microsoft.com/en-us/library/ system.exception.stacktrace.aspx



堆栈跟踪只是一个字符串,显示从throw语句到处理程序的异常传播的完整路径。通过阅读,您总能找到目的。对于日志记录,使用类 System.Diagnostics.EventLog

http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx



祝你好运,

-SA


请阅读我的评论首先,因为您的应用程序是 SQLInjection [ ^ ]易受攻击。你应该尽可能地保护你的数据。



1)

正如文档所述,连接字符串必须包含完全限定的路径数据库!

  string  connstring =  string  .Format( 数据源= {0};版本= 3;  FullPathToTheDatabaseFile); 



请注意,数据库的版本已经包括了。如果您错过了它,则使用默认版本(2)。

请参阅: https:// www .connectionstrings.com / sqlite / [ ^ ]



一些开发人员建议使用 SQLiteConnectionStringBuilder [ ^ ]以确保格式正确的字符串。

< pre lang =c#> SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
builder.FailIfMissing = true ;
builder.DataSource = FullPathToTheDatabase.db;
SQLiteConnection connection = new SQLiteConnection(builder.ConnectionString);
connection.Open();





2)

不要使用<$的数组c $ c> Klient ,电影 Egzemplarz Wypozyczenie 。而不是它,使用 List(of CustomClass)。请参阅: List< T>泛型类 [ ^ ],效率更高,更灵活,并提供了一种排序和过滤数据的方法。

另一种选择是使用自定义类集合。请参阅:演练:创建自己的收藏类 [ ^ ]


Hello. I'm programmer-beginner and I try to convert SQLite database to set of tables (like in example). What do I wrong? My constructor does't create object with correct tables.
Code of my class:

public class bazaDVD
    {
        public Klient[] Klienci;
        public Film[] Filmy;
        public Egzemplarz[] Egzemplarze;
        public Wypozyczenie[] Wypozyczenia;

        
        public bazaDVD ()
        {
            DataTable tabelkaK = new DataTable();
            DataTable tabelkaF = new DataTable();
            DataTable tabelkaE = new DataTable();
            DataTable tabelkaW = new DataTable();
            SQLiteConnection connect = new SQLiteConnection("Data SOurce = baza_wypozyczalnia.s3db");
            SQLiteDataAdapter adapterK = new SQLiteDataAdapter ("SELECT * FROM Klienci",connect);
            SQLiteDataAdapter adapterF = new SQLiteDataAdapter ("SELECT * FROM Filmy", connect);
            SQLiteDataAdapter adapterE = new SQLiteDataAdapter ("SELECT * FROM Egzemplarze", connect);
            SQLiteDataAdapter adapterW = new SQLiteDataAdapter("SELECT * FROM Wypozyczenia", connect);
            adapterK.Fill(tabelkaK);
            adapterF.Fill(tabelkaF);
            adapterE.Fill(tabelkaE);
            adapterW.Fill(tabelkaW);
            this.Klienci = DataK_TabelaK(tabelkaK);
            this.Filmy = DataF_TabelaF(tabelkaF);
            this.Egzemplarze = DataE_TabelaE(tabelkaE);
            this.Wypozyczenia = DataW_TabelaW(tabelkaW);

        }
        

        private Klient[] DataK_TabelaK (DataTable tabelaK)
        {
            for (int i=0; i<tabelaK.Rows.Count; i++)
            {
                Klienci = new Klient[tabelaK.Rows.Count];
                Klienci[i].KlientId = Convert.ToInt32(tabelaK.Rows[i][0]);
                Klienci[i].imie = Convert.ToString(tabelaK.Rows[i][1]);
                Klienci[i].nazwisko = Convert.ToString(tabelaK.Rows[i][2]);
            }
            return Klienci;
        }

        private Film[] DataF_TabelaF (DataTable tabelaF)
        {
            for (int i=0; i<tabelaF.Rows.Count; i++)
            {
                Filmy = new Film[tabelaF.Rows.Count];
                Filmy[i].FilmId = Convert.ToInt32(tabelaF.Rows[i][0]);
                Filmy[i].Rezyser = Convert.ToString(tabelaF.Rows[i][1]);
                Filmy[i].Tytul = Convert.ToString(tabelaF.Rows[i][2]);
                Filmy[i].Cena = Convert.ToInt32(tabelaF.Rows[i][3]);
            }
            return Filmy;
        }

        private Egzemplarz[] DataE_TabelaE (DataTable tabelaE)
        {
            for (int i = 0; i < tabelaE.Rows.Count; i++)
            {
                Egzemplarze = new Egzemplarz[tabelaE.Rows.Count];
                Egzemplarze[i].EgzId = Convert.ToInt32(tabelaE.Rows[i][0]);
                Egzemplarze[i].FilmId = Convert.ToInt32(tabelaE.Rows[i][1]);
            }
            return Egzemplarze;
        }

        private Wypozyczenie[] DataW_TabelaW (DataTable tabelaW)
        {
            for (int i=0; i<tabelaW.Rows.Count;i++)
            {
                Wypozyczenia = new Wypozyczenie[tabelaW.Rows.Count];
                Wypozyczenia[i].KlientId = Convert.ToInt32(tabelaW.Rows[i][0]);
                Wypozyczenia[i].EgzId = Convert.ToInt32(tabelaW.Rows[i][1]);
            }
            return Wypozyczenia;
        }
    
    }



When I try to use:

bazaDVD sthnk = new bazaDVD();
     string elo = Convert.ToString(sthnk.Klienci.Length);
     MessageBox.Show(elo);


I get

An unhandled exception of type 'System.NullReferenceException'

解决方案

Sorry, but your code is a disaster. Nevermind using SQLite, you clearly don't know how to code.

You're getting a null reference exception because Klienci is not instantiated. It's only instantiated inside this loop:

Klienci = new Klient[tabelaK.Rows.Count];


so if there are no rows, Klienci will be null.

Of course, you're instantiating for every single record, it should be instantiated outside of the loop, so you're never going to get the data into an array anyways.

And why would you want it in an array?

This:

string elo = Convert.ToString(sthnk.Klienci.Length);
MessageBox.Show(elo);


is sort of a disaster too. You could just do:

MessageBox.Show(sthnk.Klienci.Length.ToString());


or:

MessageBox.Show(String.Format("Length = {0}", n));



So, sorry to say, it's not SQLite that is the problem, it's your code.


You did not show where the exception with the message "Object reference not set to an instance of an object" is thrown.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object".

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx,
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx.

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx.

Good luck,
—SA


Please, read my comment first, becuase your application is SQLInjection[^] vulnerable. You should protect your data as much as possible.

1)
As the documentation states, connection string has to contain fully qualified path to the database!

string connstring = string.Format("Data Source={0};Version=3;", "FullPathToTheDatabaseFile");


Note that, version of database is included. In case when you missed it, the default version is used (2).
See: https://www.connectionstrings.com/sqlite/[^]

Some developers recommend to use SQLiteConnectionStringBuilder[^] to ensure a correctly formatted string.

SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
builder.FailIfMissing = true;
builder.DataSource = "FullPathToTheDatabase.db";
SQLiteConnection connection = new SQLiteConnection(builder.ConnectionString);
connection.Open();



2)
Do not use array of Klient, Film, Egzemplarz, Wypozyczenie. Rather than it, use List(of CustomClass). Please, see: List<T> generic class[^], which is more efficient, flexible, and provides a methods to sort and filter data.
Another option is to use custom class collection. See: Walkthrough: Creating Your Own Collection Class[^]


这篇关于C#和SQLite - 我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆