Insert textbox values into database table - c#

What is the easiest and most SQL-like way to insert textbox values into a SQL Server table? I found several ways, and all of them are too complicated for this simple thing I want to do.

If LINQ is too foreign for you, you can still do things the old-fashioned way:
string statement = "INSERT INTO mytable(mycolumn) VALUES (#text)";
SqlCommand command = new SqlCommand(statement);
command.Parameters.AddWithValue("#text", myTextBox.Text);
try{
SqlConnection connection = new SqlConnection(myConnectionString);
connection.Open();
command.Connection = connection;
command.ExecuteNonQuery();
} catch {
//do exception handling stuff
}
Edit: Here's another version that uses using to ensure that messes are cleaned up:
string statement = "INSERT INTO mytable(mycolumn) VALUES (#text)";
using(SqlCommand command = new SqlCommand(statement))
using(SqlConnection connection = new SqlConnection(myConnectionString)) {
try{
command.Parameters.AddWithValue("#text", myTextBox.Text);
connection.Open();
command.Connection = connection;
command.ExecuteNonQuery();
} catch {
//do exception handling stuff
}
}

If you want to do something quickly, use LINQ to SQL. It will take care of your Data Access Layer & Business objects.
Just go to LINQ to SQL Classes on Visual Studio & map your SQL server and add any tables you want to it.
Then you can use the objects it creates in your code behind to update values from textboxes.
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

public string ConnectionString
{
get
{
//Reading connection string from web.config
return ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
}
}
public bool InsertEmployee()
{
bool isSaved = false;
int numberOfRowsAffected = 0;
string query = #"INSERT INTO Employee(EmployeeName, EmailAddress)
VALUES (#EmployeeName, #EmailAddress);
SELECT ##IDENTITY AS RowEffected";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#EmployeeName", txtEmployeeName.Text));
cmd.Parameters.Add(new SqlParameter("#EmailAddress", txtEmailAddress.Text));
try
{
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
cmd.Connection = cn;
cn.Open();
object result = cmd.ExecuteScalar();
isSaved = Convert.ToInt32(result) > 0 ? true : false;
}
}
catch (Exception ex)
{
isSaved = false;
}
return isSaved;
}
But, in multiple layer or multi-tier application you do need to create DTO(Data Transfer Object) to pass the data from layer to layer(or tier to tier)

Here's a simple way to do it. It looks complex because of the number of rows: Inserting Data in SQL Database

Related

adding to database oledb c#

After searching for about an hour it appears this is the correct way to use the oledb libary to insert a record to an access database however it doesnt work for me , HELP...
InitializeComponent();
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = \\crd-a555-015.occ.local\c$\Users\james.piper\Documents\Visual Studio 2015\Projects\Project V1\Project Database.accdb";
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Work_Done (employee,client,project,task,hours)" + " VALUES (#employee,#client,#project,#task,#hours)";
cmd.Parameters.AddWithValue("#employee", user.employee);
cmd.Parameters.AddWithValue("#client", listBox1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#project", listBox2.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#task", listBox3.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#hours", listBox4.SelectedItem.ToString());
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("sql insert fail");
}
I would write this code like this:
var connectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = \\crd-a555-015.occ.local\c$\Users\james.piper\Documents\Visual Studio 2015\Projects\Project V1\Project Database.accdb";
var query = "INSERT INTO Work_Done (employee,client,project,task,hours) VALUES (#employee,#client,#project,#task,#hours)";
using (var conn = new OleDbConnection(connectionString))
{
using(var cmd = new OleDbCommand(query, conn))
{
// No need to specifiy command type, since CommandType.Text is the default
// I'm assuming, of course, your parameter data types. You should change them if my assumptions are wrong.
cmd.Parameters.Add("#employee", OleDbType.Integer).Value = user.employee;
cmd.Parameters.Add("#client", OleDbType.Integer).Value = Convert.ToInt32(listBox1.SelectedItem);
cmd.Parameters.Add("#project", OleDbType.Integer).Value = Convert.ToInt32(listBox2.SelectedItem);
cmd.Parameters.Add("#task", OleDbType.Integer).Value = Convert.ToInt32(listBox3.SelectedItem);
cmd.Parameters.Add("#hours", OleDbType.Integer).Value = Convert.ToInt32(listBox4.SelectedItem);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show($"sql insert fail: {ex}");
}
}
}
The major changes are these:
use the Using statement for each instance of a class that implements the IDisposable interface.
Using constructors with parameters to make the code shorter (and more readable, IMHO).
Note that the constructor of the OleDbCommand also has the OleDbConnection object. In your code, you didn't specify the active connection to the command.
Adding parameters with Add and not AddWithValue. Read this blog post to find out why.

SQL Queries from WCF service avoiding SQL Injection in querying a view

I have my classes from other projects which have strings for SQL queries.
See my example
public class OtherClass
{
myQuery = "SELECT * FROM v_My_View WHERE code = '#code'";
// I am targeting a view, not a stored procedure
}
My question is, if I use this in my commandText and just replace the #code with a value, is this valid argument against SQL injection?
If it is vulnerable with SQL injection - what are the other options for it?
I tried to use the
CMD.Parameters.AddWithValue("#code", _obj.code)
but it ruined my query.
I am using parameters when accessing my stored procedure, but not when accessing my views.
This is my main:
public class Main
{
public DataTable myMethod()
{
try
{
DataTable myTable = new DataTable("MyDataTable");
using (SqlCommand CMD = new SqlCommand())
{
CMD.Connection = RBOSUtil.DBConnection();
CMD.CommandType = CommandType.Text;
// this is the part I used the string from other class
CMD.CommandText = OtherClas.myQuery.Replace("#code", _obj.code);
using (SqlDataAdapter DA = new SqlDataAdapter(CMD))
{
DA.Fill(myTable);
}
}
}
catch
{
throw;
}
finally
{
//close connection
}
return myTable;
}
}
use this
public class Main
{
public DataTable myMethod()
{
DataTable myTable = new DataTable("MyDataTable");
try
{
using (SqlCommand CMD = new SqlCommand())
{
CMD.Connection = RBOSUtil.DBConnection();
CMD.CommandType = CommandType.Text;
//this is the part I used the string from other class
CMD.CommandText = OtherClas.myQuery;
CMD.Parameters.Add("#code", SqlDbType.NVarChar).value = _obj.code;
using (SqlDataAdapter DA = new SqlDataAdapter(CMD))
{
DA.Fill(myTable);
}
}
}
catch
{
throw;
}
finally
{
//close connection
}
return myTable;
}
}
declare datatable before try
You don't need quotes around the parameter name in the SQL statement:
myQuery = "SELECT * FROM v_My_View WHERE code = #code";. Otherwise what you're doing looks fine to me. It should work.
EDIT: I got confused between the original question and Ravi's answer. Somehow I missed the separator between the question and the first answer. Anyway, to answer the original question, yes, using String.Replace to replace #code with a value is subject to SQL injection vulnerabilities.
You should use SQL parameters, like the code in Ravi's answer, but you'll also need to modify the query to remove the quotes around the parameter name.

Stored procedure has no parameters and arguments were supplied

I have a function which will get the records from the database.
public List<Issue> Load_Issues()
{
SqlDataReader Sdr;
List<Issue> ObjList = new List<Issue>();
cmd.CommandText = "Get_All_Issue";
try
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
Sdr = cmd.ExecuteReader();
while (Sdr.Read())
{
// here I pull out records from database..
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
return ObjList;
}
The function I am using to bind the Gridview is as follows
public void Bind_Issues()
{
gdIssues.DataSource = Bl.Load_Issues()();
gdIssues.DataBind();
}
My stored procedure doesn't take any arguments. While the page loads for the first time it is working fine and binding the records to the gridview.
We have option to edit the records also, so what happening is after updating records I need to again bind the records to gridview. So I am again using my Load_Issues function to do it. But this time it is throwing error
Get_All_Issues has no parameters and arguments were supplied
You're most probably re-using the cmd instance in multiple places and you don't clear the parameters associated with it, thus creating the exception you're seeing.
Easiest fix would be to not re-use cmd, but if for whatever reason it's better for you, just make sure you use Clear on parameters before you execute it.
cmd.Parameters.Clear();
Try not using global connections, commands etc: open and close them within the method
public List<Issue> Load_Issues() {
//TODO: Put actual connection string here
using (SqlConnection con = new SqlConnection("Connection String here")) {
con.Open();
// Put IDisposable into using
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = con;
cmd.CommandText = "Get_All_Issue";
cmd.CommandType = CommandType.StoredProcedure;
List<Issue> ObjList = new List<Issue>();
// Put IDisposable into using
using (var Sdr = cmd.ExecuteReader()) {
while (Sdr.Read()) {
//TODO: Pull out records from database into ObjList
}
}
return ObjList;
}
}
}
Try these
exec 'stored_procedure_name'
go
or
alter proc stored_procedure_name
as
begin
--Block of Statements
end
go
or
create proc stored_procedure_name
as
begin
--Block of Statements
end
go
Where go keyword will solved your problem.

ASP.Net C# - Passing a variable into MySQL query

So I want to create a line graph with data from a MySQL table and I've managed to draw one using the code below.
However, I want to pass a variable 'moduleID' to the MySQL query and I have done so, however, I'm not sure if this is the most appropriate way to do so. Should I pass a parameter instead and if so, how do I do that?
protected void chart(int moduleID)
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string comm = "SELECT * FROM scores WHERE module_id=" + moduleID.ToString();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(comm, conn);
DataSet ds = new DataSet();
Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = 1;
Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisX.Title = "time";
Chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
Chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 100;
Chart1.ChartAreas["ChartArea1"].AxisY.Title = "%";
Chart1.ChartAreas["ChartArea1"].AxisY.TextOrientation = TextOrientation.Horizontal;
try
{
conn.Open();
dataAdapter.Fill(ds);
Chart1.DataSource = ds;
Chart1.Series["Series1"].YValueMembers = "score";
Chart1.DataBind();
}
catch
{
lblError.Text = "Database connection error. Unable to obtain data at the moment.";
}
finally
{
conn.Close();
}
}
You are right. Concatenating strings to form a query is prone to SQL injection. Use parameters like:
string comm = "SELECT * FROM scores WHERE module_id=#module_id";
MySqlCommand mySqlCommand = new MySqlCommand(comm,conn);
mySqlCommand.Parameters.Add(new MySqlParameter("#module_id", module_id));
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(mySqlCommand);
You should also enclose your connection and command object with using statement. This will ensure proper disposal of resource.
Also an empty catch is very rarely useful. You should catch specific exception first and then the base exception Exception in an object. Use that object to log the exception information or show in your error message. This will provide you help in debugging your application.
Step1: Create stored Procedure
CREATE PROCEDURE SelectScore
(#moduleID NCHAR(50))AS
SELECT * FROM scores WHERE module_id=#moduleID
Step2: Call the stored Procedure from Code
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr )) {
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("SelectScore", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#moduleID ", moduleID ));
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader()) {
// iterate through results, printing each to console
while (rdr.Read())
{
..
}
}
}

How to run a sp from a C# code?

I am new to ADO.net. I actually created a sample database and a sample stored procedure. I am very new to this concept. I am not sure of how to make the connection to the database from a C# windows application. Please guide me with some help or sample to do the same.
Something like this... (assuming you'll be passing in a Person object)
public int Insert(Person person)
{
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand dCmd = new SqlCommand("InsertData", conn);
dCmd.CommandType = CommandType.StoredProcedure;
try
{
dCmd.Parameters.AddWithValue("#firstName", person.FirstName);
dCmd.Parameters.AddWithValue("#lastName", person.LastName);
dCmd.Parameters.AddWithValue("#age", person.Age);
return dCmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
It sounds like you are looking for a tutorial on ADO.NET.
Here is one about straight ADO.NET.
Here is another one about LINQ to SQL.
This is the usual pattern (it might be a bit different for different databases, Sql Server does not require you to specify the parameters in the command text, but Oracle does, and in Oracle, parameters are prefixed with : not with #)
using(var command = yourConnection.CreateCommand())
{
command.CommandText = "YOUR_SP_CALL(#PAR1, #PAR2)";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new OdbcParameter("#PAR1", "lol"));
command.Parameters.Add(new OdbcParameter("#PAR2", 1337));
command.ExecuteNonQuery();
}
Something like this:
var connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
var conn = new SqlConnection(connectionString);
var comm = new SqlCommand("YourStoredProc", conn) { CommandType = CommandType.StoredProcedure };
try
{
conn.Open();
// Create variables to match up with session variables
var CloseSchoolID = Session["sessCloseSchoolID"];
// SqlParameter for each parameter in the stored procedure YourStoredProc
var prmClosedDate = new SqlParameter("#prmClosedDate", closedDate);
var prmSchoolID = new SqlParameter("#prmSchoolID", CloseSchoolID);
// Pass the param values to YourStoredProc
comm.Parameters.Add(prmClosedDate);
comm.Parameters.Add(prmSchoolID);
comm.ExecuteNonQuery();
}
catch (SqlException sqlex)
{
}
finally
{
conn.Close();
}
If using SQL Server:
SqlConnection connection = new SqlCOnnection("Data Source=yourserver;Initial Catalog=yourdb;user id=youruser;passowrd=yourpassword");
SqlCommand cmd = new SqlCommand("StoredProcName", connection);
cmd.CommandType=StoredProcedureType.Command;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
If not then replace Sql with Ole and change the connection string.
Here is a good starting point http://support.microsoft.com/kb/310130
OdbcConnection cn;
OdbcCommand cmd;
OdbcParameter prm;
OdbcDataReader dr;
try {
//Change the connection string to use your SQL Server.
cn = new OdbcConnection("Driver={SQL Server};Server=servername;Database=Northwind;Trusted_Connection=Yes");
//Use ODBC call syntax.
cmd = new OdbcCommand("{call CustOrderHist (?)}", cn);
prm = cmd.Parameters.Add("#CustomerID", OdbcType.Char, 5);
prm.Value = "ALFKI";
cn.Open();
dr = cmd.ExecuteReader();
//List each product.
while (dr.Read())
Console.WriteLine(dr.GetString(0));
//Clean up.
dr.Close();
cn.Close();
}
catch (OdbcException o) {
MessageBox.Show(o.Message.ToString());
}

Categories