Hi, @那由多. Welcome to Microsoft Q&A.
SqlDbType
should be specified as the type of the corresponding field in the database.
For example: If the Age
field in the database is of type Int
, then SqlDbType
should be SqlDbType.Int
.
string query = "INSERT INTO myTable (Name,Age) VALUES (@Name,@Age)";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar));
cmd.Parameters.Add(new SqlParameter("@Age", SqlDbType.Int));
cmd.Parameters["@Name"].Value = "Tom";
cmd.Parameters["@Age"].Value = 28;
cmd.ExecuteNonQuery();
}
conn.Close();
If the database field is not of NVarChar
type, using SqlDbType.NVarChar
cannot guarantee that the conversion will be successful. Sometimes a conversion failure error will occur, making the program less robust.
You could compare the document to specify the correct SqlDbType
type.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.