I have created a sql server database in godaddy and created a table named property manually.i also successfuly connected my application to the database using connection string.But i am unable to insert any values to the table using my c# code
Below is my C# code
string strQuery = "INSERT INTO property(name,email,phone,heading,description,location,image1,image2,image3,image4) VALUES('" + name + "','" + email + "','" + phone + "','" + title + "','" + description + "','" + district + "',#data,#data2,#data3,#data4);";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#data2", SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add("#data3", SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add("#data4", SqlDbType.Binary).Value = bytes4;
SqlConnection con = new SqlConnection(constr);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
Parameterize your query and clean it up a bit. Hope this helps.
using (SqlConnection con = new SqlConnection("Connection Info"))
{
// Create your parameterized command.
SqlCommand cmd = new SqlCommand("INSERT INTO [property] (name, email, phone, heading, description, location, " +
" image1, image2, image3, image4) VALUES " +
" (#name, #email, #phone, #heading, #description, #location, " +
" ,#image1,#image2,#image3,#image4)", con);
using (cmd)
{
// Set your command type.
cmd.CommandType = CommandType.Text;
// Add your parameters.
cmd.Parameters.AddWithValue("#name", "nameParamHere");
cmd.Parameters.AddWithValue("#email", "emailParamHere");
// and so on until you complete all params.
// Execute your command.
using (SqlDataReader dr = cmd.ExecuteReader()) { };
}
}
Try granting insert to your connection string "USER ID". See this link for more info...
http://beginner-sql-tutorial.com/sql-grant-revoke-privileges-roles.htm
GRANT INSERT
ON [property]
TO {user_name}
[WITH GRANT OPTION];
Related
Create to check for the duplicated name before being entered in the database)
private void btn_Submit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
if (txt_Name.Text == "Employee")
{
cmd.ExecuteNonQuery();
con.Close();
display_data();
MessageBox.Show("Name existed");
}
else
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Employee values('" + txt_Name.Text + "','" + txt_Contact.Text + "','" + txt_Address.Text + "','" + txt_Email.Text + "','" + txt_Password.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
display_data();
MessageBox.Show("Inserted successfully");
}
}
It is a security risk to concat the string with the parameters, use the sqlcommand parameters instead https://learn.microsoft.com/de-de/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=dotnet-plat-ext-6.0
Example:
var query = "INSERT INTO Employee VALUES (#name, #contact, #address, #email, #password)";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#contact", txt_Contact.Text);
cmd.Parameters.AddWithValue("#address", txt_Address.Text);
cmd.Parameters.AddWithValue("#email", txt_Email.Text);
cmd.Parameters.AddWithValue("#password", txt_Password.Text);
There are several ways to the goal for your problem
Unique Index
You can add an unique index on the table, this throws an exception when executing the command
Transact-SQL
It is also possible to move the whole verification logic to the database server
https://dba.stackexchange.com/questions/125886/check-if-a-user-exists-in-a-sql-server-database
IF NOT EXISTS (SELECT * FROM Employee WHERE Name = #name)
BEGIN
INSERT INTO Employee VALUES (#name, #contact, #address, #email, #password)
END
Query before insert
Execute a second query with a filter by name and check if a row exists. However, this is not an absolute protection. Duplicate data can still occur here with parallel executions.
If you start a transaction you could secure this block but this would restrict the database access for other users during this time. https://learn.microsoft.com/en-us/sql/relational-databases/sql-server-transaction-locking-and-row-versioning-guide?view=sql-server-ver16
You can get the number of rows with the same name. If it is greater than zero, do not add new row...
But the better way is to create a UNIQUE INDEX for the name column in sql like:
CREATE UNIQUE INDEX uidx_pid
ON Employee(name);
then on c# code:
string sqlQuery = "insert into Employee values('" + txt_Name.Text + "','" + txt_Contact.Text + "','" + txt_Address.Text + "','" + txt_Email.Text + "','" + txt_Password.Text + "')";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery , con))
{
try
{
con.Open();
cmd.ExecuteNonQuery();
display_data();
MessageBox.Show("Inserted successfully");
}
catch(Exception ex) {
display_data();
MessageBox.Show("Name existed");
};
}
}
I am actually trying to get the primary key after the insertion by using ExecuteScalar(). Since it returns the first column of the first row after the insertion. But I am getting 0. I do not know why it is happening. Please help me out.
query = "Insert into Admissions(Admission_date, Student_name, Father_name, Mother_name, DOB, Gender, Address, State, City, Pincode, Admission_for, Previous_school, Fees) values ('" + txtAdmDate.Text + "','" + txtStudentName.Text + "','" + txtFatherName.Text + "','" + txtMotherName.Text + "','" + dob + "','" + gender + "','" + txtAddress.Text + "','" + txtState.Text + "','" + txtCity.Text + "','" + txtPincode.Text + "','" + cmbClass.Text + "','" + txtPreviousSchool.Text + "','" + txtFees.Text + "')";
cmd = new SqlCommand(query, con);
con.Open();
int admid = Convert.ToInt32(cmd.ExecuteScalar());
There are some issues with your code/question.
Your code is vulnerable to SQL Injection attacks. You need to parameterize your queries.
The INSERT statement by design is not meant to return anything, if you want to return the primary key of what you just inserted you need an output parameter in your query (better yet, a stored procedure).
A quick google for "return primary key on sql insert c#" would have given you a ton of results. Your question is asked almost verbatim here. In fact my answer is basically the top answers code (modified for your use).
Here is my answer
//Create an Admission class that represents your data
public static int Save(Admission admission)
{
var conn = DbConnect.Connection();
const string sqlString = "Admissions(Admission_date, Student_name, Father_name, Mother_name, DOB, Gender, " +
"Address, State, City, Pincode, Admission_for, Previous_school, Fees) values (#AdmissionDate, #StudentName, " +
"#FatherName, #MotherName, #DOB, #Gender, #Address, #State, #City, #Pincode, #AdmissionFor, #PreviousSchool, " +
"#Fees) SELECT SCOPE_IDENTITY()";
using (conn)
{
using (var cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.AddWithValue("#AdmissionDate", admission.AdmissionDate);
cmd.Parameters.AddWithValue("#StudentName", admission.StudentName);
cmd.Parameters.AddWithValue("#FatherName", admission.FatherName);
cmd.Parameters.AddWithValue("#MotherName", admission.MotherName);
cmd.Parameters.AddWithValue("#DOB", admission.DOB);
cmd.Parameters.AddWithValue("#Gender", admission.Gender);
cmd.Parameters.AddWithValue("#Address", admission.Address);
cmd.Parameters.AddWithValue("#State", admission.State);
cmd.Parameters.AddWithValue("#City", admission.City);
cmd.Parameters.AddWithValue("#Pincode", admission.Pincode);
cmd.Parameters.AddWithValue("#AdmissionFor", admission.AdmissionFor);
cmd.Parameters.AddWithValue("#PreviousSchool", admission.PreviousSchool);
cmd.Parameters.AddWithValue("#Fees", admission.Fees);
cmd.CommandType = CommandType.Text;
conn.Open();
return (int)(decimal)cmd.ExecuteScalar();
}
}
}
Try using an OUTPUT clause in your SQL command to return information about your command.
public int NewProperty(PropertyData propertyData)
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("InsertUpdateProperty", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", propertyData.ID);
cmd.Parameters.AddWithValue("#ListPropertyFor", propertyData.ListPropertyFor);
cmd.Parameters.AddWithValue("#PropertyTypeId", propertyData.PropertyTypeId);
cmd.Parameters.AddWithValue("#PropertyLoction", propertyData.PropertyLocation);
cmd.Parameters.AddWithValue("#Locality", propertyData.Locality);
cmd.Parameters.AddWithValue("#ProjectName", propertyData.ProjectName);
cmd.Parameters.AddWithValue("#PropertyDescription", propertyData.PropertyDescription);
cmd.Parameters.AddWithValue("#SuperBulidupArea", propertyData.SuperBulidupArea);
cmd.Parameters.AddWithValue("#SuperBulidupId", propertyData.SuperBulidupAreaId);
cmd.Parameters.AddWithValue("#BulidupArea", propertyData.BulidupArea);
cmd.Parameters.AddWithValue("#BulidupAreaId", propertyData.BulidupAreaId);
cmd.Parameters.AddWithValue("#CarpetArea", propertyData.CarpetArea);
cmd.Parameters.AddWithValue("#CarpetAreaId", propertyData.CarpetAreaId);
cmd.Parameters.AddWithValue("#Bathrooms", propertyData.Bathrooms);
cmd.Parameters.AddWithValue("#Bedrooms", propertyData.Bedrooms);
cmd.Parameters.AddWithValue("#Balconies", propertyData.Balconies);
cmd.Parameters.AddWithValue("#FurnishedId", propertyData.FurnishedId);
cmd.Parameters.AddWithValue("#TotalFloors", propertyData.TotalFloors);
cmd.Parameters.AddWithValue("#PropertyOnFloors", propertyData.PropertyOnFloor);
cmd.Parameters.AddWithValue("#Parking", propertyData.Parking);
cmd.Parameters.AddWithValue("#AvalibiltyId", propertyData.AvalibiltyId);
cmd.Parameters.AddWithValue("#AgeOfProperty", propertyData.AgeOfProperty);
cmd.Parameters.AddWithValue("#OwnerShip", propertyData.OwenerShip);
cmd.Parameters.AddWithValue("#Price", propertyData.Price);
cmd.Parameters.AddWithValue("#IsActive", propertyData.IsActive);
con.Open();
int i = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
return i;
}
}
I wrote the query for inserting data to MySQL table "Persons":
SqlConnection con = new SqlConnection();
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
But it's not working. I have one connection for the whole database, but it's not working for a specific table. How I can create a connection between specific table to query in C#?
What is it? SqlConnection con = new SqlConnection() you need to pass a connection string which comprises DBname, username, pasword, server name ... etc; you are not passing those information anywhere then how can you expect it to connect to your database without having the information.
Pass the connection string either in constructor or using the property.
SqlConnection con = new SqlConnection(connection_string)
(OR)
SqlConnection con = new SqlConnection();
con.ConnectionString = connection_string;
There are different ways to insert data into the tables. I suggest to use parametrized sql query to keep safe from malicious occurrence.
Firstly you should have a ConnectionString something like this:
string connectionString = "Persist Security Info=False;User ID=UserName;Password=YourPassword;Server=ServerName";
And than:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO TableName (Col1, Col2, ColN) VALUES (#Col1, #Col2, #ColN)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Col1", txtName.Text);
cmd.Parameters.AddWithValue("#Col2", txtPhone.Text);
cmd.Parameters.AddWithValue("#ColN", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
Try this code. Please edit your credentials before trying.
Replace localhost with SQL server instance name, user id with your MySQL server instance user id, password with your MySQL server instance password and testdb with your database name. It should work fine.
string connectionString = #"server=localhost;user id=admin;password=admin;database=testdb;";
SqlConnection con = new SqlConnection(connectionString);
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
Hi guys I have Access database that have some data on it and the ID is Auto Number ex ID 17 , and a Column under name phone number ex: 222 , so I want to now enter another phone number to same column phone number cuz this person have two phone number
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into data ( [Phone number] ) values ('" + textBox3.Text + "') WHERE [ID] like '" + textBox15.Text + "' ";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into [data] ( [Date],[Name] ) values ('" + textBox1.Text + "','" + textBox2.Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();
Here is a small demo of a SQL database, where one can add, update delete members from a SQL server.
There are two tables in a single SQL Server DB, one is “members” second is “overview”.
In members there is distinct ID column and members personal info like name, address telephone etc.
In overview there are only three columns which are dID, year & amount.
There is one single windows form, language is c# and project is built in Visual Studio 2010, and of course data base in SQL Server 2010.
The windows form has a “reset, insert, update & delete” buttons.
There is one more button besides the dID text box where a distinct ID can be inserted and after clicking Search button the last entry made about the member shows by filling all the text boxes where name address telephone appear. This serves the function that member full info can be seen and changes can be made or can be removed from dB.
There are two text boxes in particular, which are Year & Amount, which shows that the member has paid a certain amount for the certain year.
But as I mentioned in the text boxes you can only see the last entry made. What function I want to achieve is that after inserting dID of person x I could only in the year text box able to insert lets say any previous year and the press search which should like normally fill all the text boxes with info, and in the amount text box should show me the entry from the dB that according to the year I entered how much amount is there or there is nothing which means that may be member has not paid for a certain year.
I need help in achieving this logic programmatically therefore I would like to request assistance.
The present program is as follows :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SQLDatabase
{
public partial class SQLDBDisplay : Form
{
SqlConnection con = new SqlConnection("Data Source=JG-PC\\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=True");
public SQLDBDisplay()
{
InitializeComponent();
}
SqlDataAdapter da;
DataSet ds = new DataSet();
private void btnSearch_Click(object sender, EventArgs e)
{
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
try
{
string sql = "SELECT * FROM members where dID = '" + txtdID.Text + "' ";
txtYear.Text = sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
sql = "SELECT * FROM Overview where dID = '" + txtdID.Text + "' ";
txtYear.Text = txtYear.Text + " : " + sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtYear.Text = reader["Year"].ToString();
txtAmount.Text = reader["Amount"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnReset_Click(object sender, EventArgs e)
{
txtdID.Text = ""; txtName.Text = ""; txtAddress.Text = "";
txtMobile.Text = ""; txtEmail.Text = ""; txtYear.Text = "";
txtAmount.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO members (dID, Name, Address, Email, Mobile) VALUES ( '" + txtdID.Text+ "','" + txtName.Text + "','"
+ txtAddress.Text + "', '" + txtEmail.Text + "', '" + txtMobile.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Overview (dID, Year, Amount) VALUES ('"+ txtdID.Text +"' ,'" + txtYear.Text + "','" + txtAmount.Text +
"')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Scuessfully!!!");
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "Update members set Name = '" + txtName.Text + "', Address = '" + txtAddress.Text + "', Email = '" +
txtEmail.Text + "', Mobile = '" + txtMobile.Text + "' WHERE dID = '"
+ txtdID.Text + "'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "Update overview set Year = '" + txtYear.Text + "', Amount = '" + txtAmount.Text + "' WHERE dID = '"+ txtdID.Text+"'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data Scuessfully Updated");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM members WHERE dID = '"+ txtdID.Text +"'";
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "DELETE FROM overview WHERE dID = '" + txtdID.Text + "'";
cmd.ExecuteNonQuery();
da = new SqlDataAdapter(cmd);
MessageBox.Show("Record Scuessfully Deleted !");
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
} }
To add a solution to the comments people have made regarding parameters and sql injection, i tend to use the code below when connecting to any database.
using(SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
try
{
using(SqlCommand command = new SqlCommand())
{
command.CommandText = "SELECT * FROM members where dID = #MyId";
command.Connection = connection;
// Set the SqlDbType to your corresponding type
command.Parameters.Add("#MyId", SqlDbType.VarChar).Value = txtdID.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
}
}
finally
{
connection.Close();
}
}
You need to group your SELECT on the Amount column. A simple answer to your question would be to modify your second select query like this:
sql = "SELECT Year, dID, SUM(Amount) as Amount FROM Overview where dID = '" + txtdID.Text + "' AND Year = " + txtYear.Text + "GROUP BY amount";
Probably, you would like to use the txtYear.Text value for an SQL parameter, so:
txtYear.Text = sql;
and
txtYear.Text = txtYear.Text + " : " + sql;
don't make too much sense in your code.
Of course, this is not the correct way, as it is prone to SQL Injection. I would recommend you to use SQL Stored Procedures, which are definitely safer regarding SQL Injection.
Another improvement to the code quality would be that you should use using statements to enclose the SQLConnection, SQLCommand and SQLDataReader objects initializations.