Is it possible to add from a single textbox to different tables in a database.
I have a addclub webform and i would like to add clubname to a number of different tables.
The following is my current code that i have.
cmd = new SqlCommand("insert into youthclublist(youthclubname, description, address1, address2, county, postcode, email, phone) values ('" + youthclubname.Text + "', '" + description.Text + "','" + address1.Text + "','" + address2.Text + "', '" + county.Text + "', '" + postcode.Text + "', '" + email.Text + "', '" + phone.Text + "')", connection);
It is possible yes but consider my point below:
Think about normal form, it should be possible to design the database so that you only need to alter it on one place. If you have to change the name in several places it is likely not following normal form and the database could be redesigned.
The way you are doing the update is not advisable, have a look into SQLInjection attacks as the above code is vulnerable to this. Using parameters in the SQLCommand rather than creating a big string is a better way to do this from a security and performance point.
Hope I have not been too negative
Andy
You can do it if you use a transaction (and you should use parameters to get around some SQL injection attack problems) like so (this means that all the inserts are done in a single block on the database which is safer than doing them one after the other):
using (var cmd = new SqlCommand("BEGIN TRANSACTION;"
+ "INSERT INTO youthclublist(youthclubname) VALUES (#youthclubname);"
// Add all your INSERT statements here for the other tables in a similar way to above (I simplified it to show just one column, but you get the idea)
+ "COMMIT;", conn))
{
// Add your parameters - one for each of your text boxes
cmd.Parameters.Add("#youthclubname", SqlDbType.NVarChar).Value = youthclubname.Text;
// execute the transaction
cmd.ExecuteNonQuery();
}
Related
While inserting values into the database i am getting error which is said in subject dont know what i am missing.
string ImagePath = "";
string str = "insert into AdminAssistant() values('"+TextBox7.Text+ "','" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + DropDownList2.Text + "','" + TextBox4.Text + "','" + DropDownList1.Text+ "','" + TextBox9.Text + "','"+ImagePath+"','"+DateTime.Now+"','Active')";
SqlCommand cmd = new SqlCommand(str,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Admin Created Successfully.....!!!";
Below is the Query
Create Table AdminAssistant
(
A_ID int identity(1,1) not null primary key,
Aname varchar(20),
Aphone varchar(16),
Amail varchar(20),
A_Address varchar(150),
A_City varchar(20),
A_Gender varchar(10)NOT NULL CHECK (A_Gender IN('Male', 'Female')),
A_Password varchar(20),
Aroll varchar(20)NOT NULL CHECK (Aroll IN('SuperAdmin', 'Admin')),
MetaDescription varchar(256),
Media varchar(40),
RegisterDate datetime,
A_Status varchar(20)NOT NULL CHECK (A_Status IN('Active', 'Disable'))
)
I think this values should inserted into database despite that it is giving error.
The error is probably caused by the presence of the parenthesys after the name of the table, but this is a simple fix to do.
Your real problem lies in the string concatenation for your values.
This is a no-no in the sql world because it could be the source of many parsing bugs (for example, the presence of a single quote in the values could break the syntax and DateTime.Now is converted to a string following rules the not always are understood by the sql parser engine).
But most important is the possibility of Sql Injection.
Here some links to start your discovery for this big security risk
How can I explain Sql Injection without technical jargon.
How does the SQL injection from the “Bobby Tables” XKCD comic work?
So the only fix is through a parameterized query.
string str = "insert into AdminAssistant
(Aname,Aphone,Amail,A_Address,A_City,A_Gender,A_Password,
Aroll,MetaDescription,Media,RegisterDate,A_Status)
values(#name,#phone,#mail,#address,#city,#gender,#pass
#roll,#descr,#media,#regdata,'Active')";
using(SqlConnection con = new SqlConnection(......))
using(SqlCommand cmd = new SqlCommand(str, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = TextBox7.Text;
... other varchar parameters
cmd.Parameters.Add("#regdataq", SqlDbType.DateTime).Value = DateTime.Now;
... complete the parameters collection
cmd.ExecuteNonQuery();
}
And, I have forget to talk about storing passwords in clear text into a database. This is another very important consideration for your security. Here another link with useful info
Best way to store password in database
I have developed one app using phonegap. I want to insert the data using the phonegap sqlite. I have got the bulk of data from server using web service. Now I want to insert the service response data into local database.
for(var i=0;i<serviceResponse.length;i++)
{
var insertQuery = "";
insertQuery = "INSERT INTO PREFERENCE(ID,NAME,TYPE,VALUE,ISFAVORITE,RANK) VALUES (" + "'" + serviceResponse[i].prefid + "','" + serviceResponse[i].name + "','" + serviceResponse[i].type+ "','" + serviceResponse[i].ispreference+ "','" +serviceResponse[i].isfavorite+ "','"+serviceResponse[i].rank + "')" ;
dbinsert.transaction(function insertUserPrefDB(tx){
tx.executeSql(insertQuery);
},errorCB);
if(i==(serviceResponse.length-1))
{
alert("Pref Inserted Successfully");
}
}
What is my problem here is,
This code will insert the last record in local database. If the service response having 10 records that time the local db also having 10 records but all records are same (i.e.last record return from service).
Please help me.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
This is my first time working with DB.
I've decided to create a DB with two tables - "Team", "Player"
I want to add a new player to the "Player" table.
The "Player" table consists of the following columns: ID(autonumber), FirstName, LastName, TeamID
In order to do so, I've created three text boxes for the FirstName, LastName, TeamID
Note that I did not treat the "ID" since it's an autonumber and should be added automatically
The Button1_click should add the new row eventually.
Here's my code:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
connection = new OleDbConnection(connectionString);
}
catch
{ }
try
{
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO Player VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')");
command.ExecuteNonQuery();
connection.Close();
}
catch
{ }
When you write an INSERT string that doesn't include the column names you should specify every column in the values. In your case you need to add
string sqlText = "INSERT INTO Player (FirstName, LastName, TeamID) VALUES ('"
+ TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')");
However this code is wrong for another reason. Never write sql strings concatenating input text typed by the user. This will cause errors or, worse, lead to Sql Injection
using(connection = new OleDbConnection(connectionString))
{
connection.Open();
string sqlText = "INSERT INTO Player (FirstName, LastName, TeamID) " +
"VALUES (?, ?, ?)";
OleDbCommand command = new OleDbCommand(sqlText, connection);
command.Parameters.AddWithValue("#First", textBox1.Text);
command.Parameters.AddWithValue("#Last", textBox2.Text);
command.Parameters.AddWithValue("#team", textBox3.Text);
command.ExecuteNonQuery();
}
There is another problem. If the TeamID field is a numeric field you need to convert the textbox3.text input in a numeric value to correctly use the AddWithValue method
int teamID;
if(!Int32.TryParse(textBox3.Text, out teamID))
throw new ArgumentException("Type a valid TeamID number, please!");
command.Parameters.AddWithValue("#team", teamID);
If TeamID is a number, you don't need quotes around it.
OleDbCommand command = new OleDbCommand("INSERT INTO Player VALUES ('" + TbFirstName.Text + "','" + TbLastName.Text + "'," + TbTeamID.Text + ")");
Note: I renamed the textboxes to reduce ambiguity.
While this is probably your first pass at this, you should really sanitize your inputs. At the bare minimum create a function to replace single quotes with a double single quote.
protected string SanitizeSQL(string txt) {
return txt.replace("'", "''");
}
OleDbCommand command = new OleDbCommand("INSERT INTO Player VALUES ('" + SanitizeSQL(TbFirstName.Text) + "','" + SanitizeSQL(TbLastName.Text) + "'," + SanitizeSQL(TbTeamID.Text) + ")");
Your insert command should specify the columns it's updating, so it should be:
INSERT INTO Player(FirstName,LastName,TeamID) VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')"
Also note that concatenating text from user input directly into a query opens you up to sql injection attacks.
I am trying to get From date and To date in two text boxes using the calender control and then trying to insert this value in a table. How can I proceed with this??
Please help..
string comstr = "insert into ATM_DETAILS_TB values(" + txtpin.Text + ",'" + Convert.ToDateTime(txtvldfrm.Text) + "','" + Convert.ToDateTime(txtvldto.Text) + "'," + Convert.ToInt32(ddlaccno.SelectedValue) + ",'" + Session["strUid"].ToString() + "')";
while using this code it shows error like "String was not recognized as a valid DateTime"
what should I do??
Use Validation controls to validate that the values in textbox values are valid dates.
Your code us contencating strings directly from user input. This opens you up to all sorts of nasty attacks, the primary being SQL Injection. Use parameterized queries instead.
Always use DateTime.TryParse or TryParseExact method to parse the date.
DateTime vldDate;
bool isValid=false;
if(DateTime.TryParse(txtvldfrm.Text,out vldDate))
{
isValid=true;
}
....
if(isValid)
{
command.Parametter.Add("#vldto",SqlDbType.DateTime).Value=vldDate;
command.Parametter.Add("#strUid",SqlDbType.VarChar,30).Value=Session["strUid"];
.....
}
You Use from parameterized queries like this:
string comstr = "insert into ATM_DETAILS_TB values(#pin,#vldfrm,#vldto,#ddlaccno,#strUid)";
YourCommand.Parametter.AddWithValue("#vldto",Convert.ToDateTime(txtvldto.Text));
YourCommand.Parametter.AddWithValue("#strUid",Session["strUid"].ToString());
....Define the Other Paraametter
Edit----
check this question String was not rec...
I have written this code in visual basic. On executing no error is printed but the new row is not added to the database. I have tried using datasets also but that didnt work either. Any ideas?
Dim conSQL As SqlConnection = New SqlConnection
conSQL.ConnectionString = "Data Source=USER-PC\SQLEXPRESS;Initial Catalog=Phd;Integrated Security=True"
conSQL.Open()
Dim cmd As New SqlCommand("Insert into Phd_Student(student_id,student_name,student_email) values ('" + idnotextbox.Text + "','" + studnametextbox.Text + "','" + studemailtextbox.Text + "')" , conSQL)
cmd.ExecuteNonQuery()
There are only two possible outcomes of executing an insert; either it adds a record or you get an exception. So the alternatives in your case are:
The code that you showed is not executed at all.
You are catching the exception and ignoring it.
The actual code that you have is something different from what you posted.
You have created a trigger in the database that removes the record.
One of the values in the textboxes uses SQL injection to remove the added value*.
*) If you enter the value -1','','');delete Phd_Student where student_id='-1'-- in the id textbox, that would add a record and then remove it.
1- You should open the connection before executing the command.
try
conSQL.open()
Dim cmd As New SqlCommand("Insert into Phd_Student(student_id,student_name,student_email) values ('" + idnotextbox.Text + "','" + studnametextbox.Text + "','" + studemailtextbox.Text + "')" , conSQL)
cmd.ExecuteNonQuery()
Finally
conSQL.close()
end try
2- you should pass parameters to the query not like this way, to avoid SQL Injection.
first thing, make sure to call conSQL.Close() after cmd.ExecuteNonQuery() line.