简体   繁体   中英

Insert Records into SQL Server Database using C# Data Objects

I'm trying to properly bind a Data Adapter to my SQL database to insert records submitted by a person in ac# program. I feel like I am 80% of the way, but now i've hit a hitch.

So as in the code below, I can create and bind a Data Table just fine. I've tested the delete functions and they work just fine. I am now attempting to have a 'save' button insert a new row to my database. The problem I have now is that a user is supposed to put in their 'notes' and then hit save. I auto populate the rest of the columns, but I do not know how to grab the notes that the user entered.

Here is my code so far:

string userVerify = User.CurrentUser.UserName.ToString();
int participantID = this.mParticipant.ParticipantID;
DateTime date = DateTime.Now;
string properRow = dtNotes[1, dtNotes.NewRowIndex - 1].Value.ToString();

sqlDataAdapter.InsertCommand = new SqlCommand("INSERT INTO xxMyDatabasexx (ParticipantID,Verifier,Notes,Date) VALUES  (@participantID,@notes, @userVerify,@date);");
sqlDataAdapter.InsertCommand.Parameters.AddWithValue("@participantID", participantID);
sqlDataAdapter.InsertCommand.Parameters.AddWithValue("@userVerify", userVerify);
sqlDataAdapter.InsertCommand.Parameters.AddWithValue("@date", date);
sqlDataAdapter.InsertCommand.Parameters.AddWithValue("@notes", properRow);

sqlDataAdapter.Fill(dataTable);

sqlDataAdapter.Update(dataTable);

I am aware that the properRow variable's logic is wrong. Of course if there are no rows then the program will crash, but also if no new note has been entered it will just reproduce the last note entered which of course is wrong as well. When i look into my dataTable at the time of sqlDataAdapter.Fill, I can see the note in the correct column but I don't know how to simply save it.

Any help is appreciated. Thanks.

EDIT: What I was unaware of is that the InsertCommand (naturally) also needs the ExecuteNonQuery command with it. I was under the assumption that since both Delete and Update did not, that Insert wouldn't either. This seemed to fix the issue. Thanks all for the help.

You can insert the record into SQL Database without need for DataAdapter just by using Command object as shown in the following code snippet (just pass your Insert SQL statement string):

void SqlExecuteCommand(string InsertSQL)
{
    try
    {
        using (SqlConnection _connSqlCe = new SqlConnection("Conn String to SQL DB"))
        {
            _connSql.Open();
            using (SqlCommand _commandSqlCe = new SqlCommand(CommandSQL, _connSql))
            {
                _commandSql.CommandType = CommandType.Text;
                _commandSql.ExecuteNonQuery();
            }
        }
    }
    catch { throw; }
}

The general format of SQL INSERT query string is shown below:

INSERT INTO YourTable (column1,column2,column3,...)
VALUES (value1,value2,value3,...);

You can further extend this solution by adding parameters to the SQL String/Command in order to protect against possibility of SQL injection (see the following example):

INSERT INTO YourTable (column1,column2,column3,...)
VALUES (@param1,@param2,@param3,...);

_commandSql.Parameters.Add("@param1","abc");
_commandSql.Parameters.Add("@param2","def");
_commandSql.Parameters.Add("@param3","ghijklm");

You can also use the alternative syntax for SQL Parameters , like for eg:

_commandSql.Parameters.Add("@param1", SqlDbType.NChar).Value = "abc";
_commandSql.Parameters.Add("@param2", SqlDbType.NChar).Value = "def";
_commandSql.Parameters.Add("@param3", SqlDbType.NVarChar).Value = "ghijklm";

Pertinent to your particular question, it should be like:

"INSERT INTO xxMyDatabasexx (ParticipantID, Verifier, Notes, [Date]) VALUES  (@participantID, @userVerify, @notes, @dt)"

 _commandSql.Parameters.Add("@ParticipantID",SqlDbType.NChar).Value= participantID;
 _commandSql.Parameters.Add("@userVerify",SqlDbType.NChar).Value= userVerify ;
 _commandSql.Parameters.Add("@notes",SqlDbType.NVChar).Value= properRow ;
 _commandSql.Parameters.Add("@dt",SqlDbType.DateTime).Value= DateTime.Now;

Note : in case ParticipantID is the IDENTITY (ie Autonumber) Column, then do not include it in INSERT statement.

Hope this may help.

It seems to me that You are a bit lost. The way adapters are meant to work is

  • fill table from database via adapter (or take empty table)
  • bind table to GUI or manually transfer the information to GUI
  • change/add/delete data in table via binding or manually
  • update changes (inserts/updates/deletes) into database via adapter

The changes in table are automatically traced, so the adapter knows, what should be updated/inserted/deleted and use appropriate commands.

If You use adapter just as a holder for command You can ExecuteNonQuery with arbitrary parameters, You pass the whole concept and do not need adapter at all (see @AlexBells answer).

Apart from this, are You really going to write all that plumbing code by hand? Life is too short. If I were You, I would look for some ORM. You get simple CRUDs or concurrency checking with no effort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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