Lyndon Broz Tonelete
Lyndon Broz Tonelete

Reputation: 163

Error on Inserting data into database

I have 3 Textboxes called, TxtFirstName, TxtMiddleName and TxtLastName. I would like to insert this info to the database where my column name is just FullName. I would want my 3 Information to join to insert them into one. What I did is :

string _fullname = _lastname + "," + _firstname + middlename;
cmd = new SqlCommand("INSERT INTO TableVote (FullName) VALUES ('" + _fullname + "')", sc);

but it seems that it gets me an error. "String or Binary data would be truncated. The Statement has been terminated."

How do i correct this ?

Upvotes: 0

Views: 90

Answers (2)

ChrisWue
ChrisWue

Reputation: 19060

The error means that your string is longer than the maximum length allowed for the column. You either need to adjust your schema to allow longer values or truncate the value you insert.

Also: You should really use parametrized commands:

cmd = new SqlCommand("INSERT INTO TableVote (FullName) VALUES (@fullname)");
cmd.Parameters.AddWithValue("@fullname", _fullname);

Read up on Sql Injection attacks.

Update: As mentioned by others you should contemplate storing the name in different columns (i.e. FirstName, MiddleName, LastName. Otherwise you throw away information which will be hard to recompute (e.g. try making a statistic of the most common middle name with your schema).

Upvotes: 4

SouthShoreAK
SouthShoreAK

Reputation: 4296

As already noted, the value you are inserting into your table is too long for the column specification.

HOWEVER

I've been working with databases for quite a while now, and I'd like to advise you to please not store the name all in one column. I've seen this over and over again. It seems like a good, quick idea at the time, but sooner or later, you'll have a requirement where you need to get just part of the name. Once you reach that point, you'll find yourself with all kinds of problems, because names are very, very complicated things that are highly dependent on language and culture. Given a list of whole names, think about how you would parse out just the last names. At first, it seems very simple, until you consider all the special cases, like people with two last names ("Harper-Smith"), last names from other cultures ("St. James", "O'Connell", "Van der Wall"), etc.

Just consider saving the name in three parts in three columns, it doesn't take much and it will save you a lot of trouble later.

Upvotes: 0

Related Questions