【发布时间】:2015-05-11 17:47:02
【问题描述】:
我遵循this 教程,并尝试在 C# 控制台应用程序中使用 Access 数据库。
我有 2 节课:
class Ac
{
OleDbConnection connection;
OleDbCommand command;
private void ConnectTo()
{
connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.15.0;Data Source=D:\Info\csharp\socket\ef\accesstest\accesstest\bin\Debug\Database.accdb;Persist Security Info=False");
command = connection.CreateCommand();
}
public Ac()
{
ConnectTo();
}
public void Insert(string a, string b)
{
try
{
command.CommandText = "INSERT INTO Persons (nName, nNamee) VALUES (\"" + a + "\", \"" + b + "\");";
command.CommandType = System.Data.CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
}
还有,
namespace accesstest
{
public class MainClass
{
Ac f = new Ac();
public static void Main()
{
f.Insert("ab", "ac");
Console.WriteLine("\n\nPress enter to close...");
Console.ReadLine();
}
}
}
我得到“非静态字段、方法或属性‘accesstest.MainClass.f’需要对象引用”。 我尝试从中删除静态,但不起作用,说 Main 必须是静态的。
对我有什么想法吗?谢谢!
【问题讨论】:
-
使
f静态static Ac f = new Ac();。 -
或者把它移到
Main方法里面。 -
我想说将
f的实例创建移到main中更有意义 - 它似乎在其他任何地方都没有任何用途。 -
好的,我会的。感谢您的建议。