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
}
}
}
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 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();
}
}
Is it possible to insert xml data in to an xmltype field?
I am using the following code but is throwing an error
ORA-01461: can bind a LONG value only for insert into a LONG column
.
I do not want to use ODP.NET. Can somebody give any suggestion?
OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["OracleVAT"].ConnectionString);
try
{
string query = "update c_xml set DATA_XML = xmltype(?) where id=?";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#DATA_XML", DATAXML.OuterXml);
cmd.Parameters.AddWithValue("#id", ID);
con.Open();
return cmd.ExecuteNonQuery();
}
catch
{
}
finally
{
con.Close();
}
You can also use the standard java api:
Something like this:
string query = "update c_xml set DATA_XML = xmltype(?) .....
Clob clob = conn.createClob();
clob.setString(1, req_param_xml);
statement.setClob(2, clob);
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
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID); SELECT CAST(scope_identity() AS int)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
int lastID = (int)command.ExecuteScalar();
}
Without the
SELECT CAST(scope_identity() AS int)
One row is inserted. But since I need the ID from the created row im using scope_identity. However, when I use this, 2 rows are created instead of one.
Did I miss something?
Thanks
The problem in the code you've posted is that you run 2 times the same query... one with ExecuteNonQuery(); and the last with (int)command.ExecuteScalar();
If you try to use only the executeScalar i think you have the result's you want....
Try and hope this helps...
If you want you can use Parameter to retrieve the Identity, like they do in this Article
If you would use gbn or my answer from your first question, the problem shouldn't occur.
Try doing
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID);";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
query = "SELECT CAST(scope_identity() AS int)";
command = new SqlCommand(query, connection);
int lastID = (int)command.ExecuteScalar();
}