i want to insert special character into sqlserver 2008 database. for example ('/##&*$) etc.
i have tried the following code but it remove these string from the orignal string.
string[] arrtime = postingtime.Split(',');
string sss = arrtime[1];
string sss1 = "EDT";
bool first2 = true;
string s33 = Regex.Replace(sss, sss1, (m) =>
{
if (first2)
{
first2 = false;
return "";
}
return sss1;
});
But i didnt want to remove these string from the orignal string...because i want to insert a franch language data and removal of these special character will change the meaning of sentence.
my insert query is:
cn.Open();
adp.InsertCommand = new SqlCommand("insert into ttt values('r=DE'S''C/pa-ge=1/$#')", cn);
adp.InsertCommand.ExecuteNonQuery();
cn.Close();
when i click on insert button then it gives error(datatype error).
my problem is , to insert string with special characters not to remove these character. i want to pass these characters to our sql server 2008 from c# application.
thanx in advance
Use parameterized queries like this:
using (SqlConnection cn = new SqlConnection(...))
{
cn.Open();
using (SqlCommand cmd = new SqlCommand("insert into ttt values (#testvalue)", cn))
{
cmd.Parameters.AddWithValue("#testValue", "r=DE'S'C#4593§$%");
cmd.ExecuteNonQuery();
}
}
Use parameters
adp.InsertCommand = new SqlCommand("insert into ttt values(#p1)", cn);
adp.InsertCommand.Parameters.Add(new SqlParameter("#p1", SqlDbType.NVarChar)).Value = "r=DE'S''C/pa-ge=1/$#";
Your Insert query vunlerable to SQL injections.. Try using SqlParameters. and in SQLServer User NVarchar datatype.
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("insert into ttt values(#paramValue)", con))
{
cmd.Parameters.AddWithValue("#paramValue", "r=DE'S'C#4593§$%");
con.Open();
cmd.ExecuteNonQuery();
}
}
Related
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();
}
I have some textbox which can have empty value. When I am trying to insert that textbox.text in insert command then it show error in sql. I want the automatic check when textbox is empty it will insert null in database in sql server 2008 R2. I am using normal insert into command and I do not want to use procedure(too clumsy).
please help me anyone.
Thanks in advance.
Not really sure about your code, but it should be like:
using (SqlConnection conn = new SqlConnection("ConnectionString"))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "INSERT into yourTable(ID, Col1, Col2) VALUES (#ID, #Col1, #Col2);";
cmd.Connection = conn;
conn.Open();
cmd.Parameters.AddWithValue("#ID", yourID);
cmd.Parameters.AddWithValue("#Col1", string.IsNullOrWhiteSpace(textBox1.Text) ?
DBNull.Value: textBox1.Text);
cmd.Parameters.AddWithValue("#Col2", string.IsNullOrWhiteSpace(textBox2.Text) ?
DBNull.Value : textBox2.Text);
cmd.ExecuteNonQuery();
}
You can check for Empty String using string.IsNullOrWhiteSpace, pass null accordingly. Use string.IsNullOrEmpty(), if you want to consider spaces as valid values.
If you are using direct insert query
"insert into table_name (column1,column2,column3) values("+column1value+","+column2value+","+textbox.Text.Trim()!=""?textbox.Text.Trim():DBNull.Value+")";
Even if you are using parameterised query, you can use the same expression
textbox.Text.Trim()!=""?textbox.Text.Trim():DBNull.Value
Try something like this:
using (SqlConnection conn = new SqlConnecction(connStr))
{
conn.Open();
string qry = "INSERT TargetTable (TargetColumn) VALUES (#TextValue)";
using (SqlCommand cmd = new SqlCommand(qry, conn))
{
cmd.Parameters.Add(new SqlParameter("#TextValue", String.IsNullOrEmptyOrWhiteSpace(textBox.Text) ? DBNull.Value : textBox.Text));
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException sex)
{
// whatever
}
}
}
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
I've created a database and a table with 2 fields Id and Name.
Now I want to insert values on clicking a button the sammple code is given. it's not working.
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command =new SqlCommand("insert into Test (Id,Name) values(5,kk);",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
String values should be in quotes. This has not much to do with C#, more with T-SQL
Try this, and notice the kk;
SqlCommand command =
new SqlCommand("insert into Test (Id,Name) values(5,'kk');",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Also I am assuming here that Id is not an auto-increment field. If it is, then you should not fill it.
As a side-node you should look at parameterized queries to prevent SQL injection.
In this instance, you need single quotes ' around the kk
insert into Test (Id,Name) values(5,'kk')
In general, you should use parameterised queries
try this:
SqlConnection conn = new SqlConnection();
SqlTransaction trans = conn.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand("insert into Test (Id,Name) values(#iD, #Name)", conn, trans))
{
cmd.CommandType = CommandType.Text;
cmd.AddParameter(SqlDbType.UniqueIdentifier, ParameterDirection.Input, "#iD", ID);
cmd.AddParameter(SqlDbType.VarChar, ParameterDirection.Input, "#Name", Name);
cmd.ExecuteNonQuery();
}
conn.CommitTransaction(trans);
}
catch (Exception ex)
{
conn.RollbackTransaction(trans);
throw ex;
}
Try this:
SqlConnection con = new SqlConnection('connection string here');
string command = "INSERT INTO Test(Id, Name) VALUES(5, 'kk')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
String values should be between ' '
Verify your connection string
//add your connection string between ""
string connectionString = "";
using (var conn = new SqlConnection(connectionString))
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO pdf (Id, Name) VALUES (5, 'kk')";
conn.Open();
conn.ExecuteNonQuery();
conn.Close();
}
It looks like you have multiple problems with your current code.
You need to enclose string values in single quotes, as pointed out in other answers.
You need to enable remote connection to your SQL server.
Check the following link if you are using SQL server 2008.
How to enable remote connections in SQL Server 2008?
and for SQL Server 2005 see:
How to configure SQL Server 2005 to allow remote connections
I want to create a GUID and store it in the DB.
In C# a guid can be created using Guid.NewGuid(). This creates a 128 bit integer. SQL Server has a uniqueidentifier column which holds a huge hexidecimal number.
Is there a good/preferred way to make C# and SQL Server guids play well together? (i.e. create a guid using Guid.New() and then store it in the database using nvarchar or some other field ... or create some hexidecimal number of the form that SQL Server is expecting by some other means)
Here's a code snippet showing how to insert a GUID using a parameterised query:
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using(SqlTransaction trans = conn.BeginTransaction())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
cmd.CommandText = #"INSERT INTO [MYTABLE] ([GuidValue]) VALUE #guidValue;";
cmd.Parameters.AddWithValue("#guidValue", Guid.NewGuid());
cmd.ExecuteNonQuery();
trans.Commit();
}
}
SQL is expecting the GUID as a string. The following in C# returns a string Sql is expecting.
"'" + Guid.NewGuid().ToString() + "'"
Something like
INSERT INTO TABLE (GuidID) VALUE ('4b5e95a7-745a-462f-ae53-709a8583700a')
is what it should look like in SQL.
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "#guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
Store it in the database in a field with a data type of uniqueidentifier.
// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("#orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("#statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("#read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("#write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConnection.Close();