0

我正在尝试使用 C# 和 Access 数据库创建一个程序,并通过在每次添加时创建新行来连接并将值添加到表中,现在我遇到了这个问题,我找不到适用于我的程序的解决方案. 这是我的代码的一部分

        public string connstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\College\Year 2\Structured Programming\Go Greece Ver.1\Database\GoGreece.accdb;Persist Security Info=False;";

        private void savebutton_Click(object sender, EventArgs e)
        {
            {

                OleDbConnection hotelConn = new OleDbConnection(connstr);
                InitializeComponent(); 
                OleDbCommand hotelComm = new OleDbCommand();
                OleDbDataAdapter hotelAdapter = new OleDbDataAdapter();
                DataTable hotelData = new DataTable();
                DataSet ds = new DataSet();

                hotelConn.Open();
                hotelComm.Connection = hotelConn;
                hotelComm.CommandText = " INSERT INTO Hotels (Name) VALUES ('" + nametext + "')";
                int temp = hotelComm.ExecuteNonQuery();
                if (temp > 0)
                {
                    nametext.Text = null;
                    MessageBox.Show("Successfully added into database");
                }
                else
                {
                    MessageBox.Show("Records were not added into the database");
                }
                hotelConn.Close();
4

1 回答 1

0

在我的脑海中,我认为它应该是这样的:-

string connstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\College\Year 2\Structured Programming\Go Greece Ver.1\Database\GoGreece.accdb;Persist Security Info=False;";



using (OleDbConnection con = new OleDbConnection(connstr))
        {
            string SQlstring = string.Format("INSERT INTO [Hotels] (Name) VALUES ('{0}')", nametext);
            OleDbCommand cmd = new OleDbCommand(SQlstring, con);

            try
            {
                con.Open();
                int result = cmd.ExecuteNonQuery();
            }
            catch(OleDbException Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
于 2013-02-27T11:58:43.677 回答