How to insert a row into SQL Server 2005 using C#? - c#

I am using VS 2008 and SQL Server 2005. I am using below code to insert a row to a table.
Table is TestTable, and it has a single column Name (varchar(50)).
I am new to C# coding.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string sql = "insert into TestTable(Name) values (vinayak)";
using (SqlConnection conn = new SqlConnection("Data Source=VINAYAK-PC;Initial Catalog=TestTable;Integrated Security=True;"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#Name", "test"); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
}

You haven't included the parameter in the SQL statement.
Change vinayak to #Name.

In table "TestTable" if you have only one column "Name" and you want to insert value "vinayak" in that then include vinayak in single quotes and you do not need to execute following statement -:
cmd.Parameters.AddWithValue("#Name", "test");
if you want to use parameter in your sql command then make sure u prefix "#" before "name" in your sql command.
see this link

Related

Inserting data row into a sql table from another sql table in C#

Context: I'm developing an app for windows in Visual Studio that has a table of stock materials and another of buyed materials, both in a Sql Server.
I want that every time you buy something it is added into the stock table.
I'm new in using SQL with c# combined.
I'm trying this from a tutorial, but does nothing. Not even an exception.
string cmdString = "Insert INTO Table1 (Column_name) VALUES (#val1)";
string connString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = conn.CreateCommand())
{
comm.Connection = conn;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("#val1", Value);
try
{
conn.Open();
comm.ExecuteNonQuery();
conn.Close()
}
catch(SqlException ex)
{
}
}
}
Is this totally wrong or should i change something?
Edit: I figured out. I was inserting val1 in a column, but the ID was empty so it throws an NullId exception. For some reason in debug mode I wasn't able to see it.
Thanks for the help. If I have the Table1 with autoincrement why it needs an ID? There is a way that when something is inserted the Id generates automatically?
You can use this query to insert data like that :
{
if (con.State == ConnectionState.Open)
con.Close();
}
{
SqlCommand cmd0561 = new SqlCommand(#"insert into Table1 (value1,value1) values
(#value1,#timee)", con);
cmd0561.Parameters.AddWithValue("#value1", value1.Text.Trim);
cmd0561.Parameters.AddWithValue("#value2", value2.Text.Trim);
con.Open();
cmd0561.ExecuteNonQuery();
con.Close();
}

Insert SQL data into table in ASP.Net Web Application via textbox

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace todoassignment1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Visible = false;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string valueUser = txtUsername.Text;
SqlConnection db = new SqlConnection(SqlDataSource1.ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
//User is the name of the table, UserName is the column
cmd.CommandText = "INSERT User (UserName) VALUES ('" + valueUser + "')";
cmd.Connection = db;
db.Open();
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
Label1.Text = "Success writing into database!";
Label1.Visible = true;
}
catch (Exception ex)
{
Label1.Text = "Error writing into database.";
Console.WriteLine(ex.Message);
Label1.Visible = true;
}
finally
{
db.Close();
}
}
}
}
I added the SqlDataSource1 on the Default.aspx page, which seems to be done successfully as I can see the column names of the User table in the gridview. The table is empty, and all I'm trying to do is take input in a textbox and send it to the UserName column.
I'm not very good at debugging, but I have noticed a few errors which I have spent hours researching.
Things I've tried:
SQL SMS > tools > options > designers > CHECK prevent saving changes that require table re-creation
Added using System.Data;
Added cmd.Connection.Open();
Added an exception to be caught in the catch statement
Recreate entire database
Quadruple checked things like txtUsername being the correct textbox ID
Reconfigure SqlDataSource1 over and over, delete and recreate
Confirm that the connectionString in web.config is correct
Create the new SQLConnection with the exact string in web.config
SqlConnection db = new SqlConnection("Data Source=NAME-PC\\SQLEXPRESS;Initial Catalog=Assignment;Integrated Security=True");
Changed the insert line from concatenation to just "INSERT User (UserName) VALUES ('asdf')" to simplify code, still doesn't work.
Tried other syntax
cmd.CommandText = "INSERT INTO User (UserName) VALUES (#username)";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 50);
cmd.Parameters["#username"].Value = txtUsername.Text.ToString();
Clues from the debugger:
saw several "System.InvalidCastExceptions when digging through cmd in autos
errorCS0103: the name 'ExecuteNonQuery' does not exist in the current context
Always see System.InvalidOperationException after running
Please help.
static void BtnSubmit_Click(object sender, EventArgs e)
{
string valueUser = "test"; //txtUsername.Text;
using (SqlConnection db = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True"))//SqlDataSource1.ConnectionString);
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.[User] (UserName) VALUES (#valueUser)", db);
cmd.Parameters.Add("#valueUser", SqlDbType.VarChar, 50).Value = valueUser;
//cmd.CommandType = CommandType.Text;
//User is the name of the table, UserName is the column
//cmd.CommandText = "INSERT User (UserName) VALUES (#valueUser)";
//cmd.Connection = db;
db.Open();
try
{
//cmd.Connection.Open();
cmd.ExecuteNonQuery();
/*Label1.Text =*/
Console.WriteLine("Success writing into database!");
//Label1.Visible = true;
}
catch (Exception ex)
{
/*Label1.Text =*/
Console.WriteLine("Error writing into database.");
Console.WriteLine(ex.Message);
//Label1.Visible = true;
}
//finally
//{
//db.Close();
//}
}
}
A couple of issues.
The syntax for insert is INSERT INTO TABLE (COLUMNS) VALUES (VALUES) You had "INSERT User (UserName)"...
USER is a reserved word in SQL. If you insist upon using it as your table name it must be wrapped in square brackets.
You were opening the connection twice. Not really a problem per se, but unnecessary.
Always, always, always be using parameters.
I simplified things a little.
If you modify the method I've attached you should be able to copy paste it.

Create Table query with SQL Server CE

Which is the best way to execute a query in C# + SQL Server CE? I need to create a table, but after 3 days of unsuccessful attempts, I realize that I really can't do it for myself... So I'm here asking for help.
I've tried these topics:
create sql table programmatically
Data Adapter Vs Sql Command
But all ways I tried show me an exception... I'm confused, where is my mistake?
My current code:
public void Connect()
{
try
{
string FileName = "DataBase";
using (SqlCeConnection myConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=Z123"))
{
string query = "create table EXP(ID int, source int)";
int i;
SqlCommand cmd = new SqlCommand(query, connection);
cmd.con.open();
i = cmd.ExecuteNonQuery();
}
}
catch (SqlCeException ae)
{
MessageBox.Show(ae.Message.ToString());
}
}
Many thanks!
If you're using SQL Server CE then you need to use a SqlCeCommand (not a SqlCommand - that's for the full-blown SQL Server).
So change your code to:
using (SqlCeConnection myConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=Z123"))
{
string query = "create table EXP(ID int, source int)";
// use SqlCeCommand here!! Also: use the "myConnection" SqlCeConnection you're
// opening at the top - don't use something else.....
SqlCeCommand cmd = new SqlCeCommand(query, myConnection);
myConnection.open();
cmd.ExecuteNonQuery();
myConnection.Close();
}

Error in creating a table in mySQL

I tried some of your suggestions but still the same error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' (size int(5))' at line 1
Here is my code:
try{
query = "CREATE TABLE #name (size int(5))";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 30).Value = txtboxName.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
i think you intended to use backticks `` to escape table name but used single quotes instead.
query = "CREATE TABLE `"+ txtboxName.Text + "`(size int(5))";
I would try to add escape sequences to txtboxName.Text. There can be some special characters, that break your SQL statement.
You missed space between table name and the column definitions
query = "CREATE TABLE "+ txtboxName.Text + " (size int(5))";
|
put space here
sql injection... don't use inline parameters. below is sample code with few best practices what I know. But you can't use parameters for table names.
public void CreateTable(string tblName)
{
using (var con = new MySqlConnection(MySqlConnectionString))
{
using (var cmd = new MySqlCommand(String.Format("CREATE TABLE {0} (size int(5))",tblName), con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
}

insert in sql using c#

this code is successfully inserting a new value in a SQL db, but only when I insert constant values.
I need help where it says **(?)** in the code below, where I want to insert new values without specifying constants in the code.
What I mean is, I want to be able to type any random value in output window and it gets inserted into the SQL db.
private void InsertInfo()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
connetionString = #"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
connection = new SqlConnection(connetionString);
string sql = "insert into record (name,marks) **values( ?))";**
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void insert_Click(object sender, EventArgs e)
{
InsertInfo();
}
There is no need to use an adapter here; that is not helping you. Just:
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString))
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "insert into record (name, marks) values (#name, #marks)";
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("marks", marks);
conn.Open();
cmd.ExecuteNonQuery();
}
or with a tool like "dapper":
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString)) {
conn.Open();
conn.Execute("insert into record (name, marks) values (#name, #marks)",
new {name, marks});
}
Those '?' are termed as parameters. From what I understand, you are wanting to use a parametrized query for your insert which is a good approach as they save you from chance of a SQL injection. The '?' sing in your query is used when you are using an
OLEDBConnection & Command object.
Normally, you would use '#' symbol to specify a parameter in your query. There is no need for an adapter. You just
//Bind parameters
// Open your Connection
// Execute your query
// Close connection
// return result
Parametrized queries 4 Guys from Rolla
MSDN: How to Protect from SQL injection in ASP.NET

Categories

Resources