简体   繁体   English

未将对象引用设置为对象的实例-错误

[英]Object reference not set to an instance of an object - error

I'm trying to insert in an Access Database, from visual C#. 我正在尝试从可视C#插入Access数据库。 But i got this error: error 但是我得到了这个错误: 错误

What am I doing wrong in code? 我在代码中做错了什么? The values are correct, they comes from the input boxes. 值正确,它们来自输入框。

Thanks! 谢谢!

From the picture it looks like the adapter.InsertCommand property is null. 从图片中看起来像是adapter.InsertCommand属性为null。
Instead of 代替

adapter.Insertcommand.CommandText = ...

use 采用

insertCommand.CommandText = ...
adapter.InsertCommand = insertCommand;

You're creating the OleDbDataAdapter adapter ok, and you're creating a (stand-alone) OleDbCommand insertCommand as well - but you're NOT creating an instance for adapter.InsertCommand - that variable will be NULL ! 您正在创建OleDbDataAdapter adapter ,还正在创建(独立的) OleDbCommand insertCommand但您没有adapter.InsertCommand创建实例-该变量将为NULL!

You need to do: 您需要做:

OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.InsertCommand = new OleDbCommand();

Create the adapter.InsertCommand instead of a stand-alone instance. 创建adapter.InsertCommand而不是独立实例。

At bottom left of picture I see "adapter.InserCommand" is null while the error occurred after you created a new "oleDbCommand" and it's the source of exception. 在图片的左下角,我看到“ adapter.InserCommand”为空,而在创建新的“ oleDbCommand”后发生了错误,这是异常的来源。 Why ? 为什么呢 Because you created one "oleDbCommand" and didn't assign it to your adapter. 因为您创建了一个“ oleDbCommand”,但未将其分配给适配器。

Anyway, the way you deal with sql is not recommended and the code is prone to sql injection attacks. 无论如何,不​​建议您使用sql进行处理,并且代码易于受到sql注入攻击。 Also putting a large amount of code inside a "Try" block is not recommended since you cannot find the source of problem later. 不建议在“ Try”块中放入大量代码,因为以后找不到问题的根源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM