save a decimal value in database c# - c#

I am trying to save a value from text box into sql database. I am having the error as shown on the picture. my code below:
public void datastore()
{
string Blerje, Shitje, Data;
Blerje = usdollar_buy.Text;
Shitje = usdollar_sell.Text;
Data = dateTimePicker.Text;
try
{
string constring = "Data Source=DELL;Initial Catalog=login_register;Integrated Security=True";
/* Declaring Connection Variable */
SqlConnection con = new SqlConnection(constring);
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
/* Checking Connection is Opend or not If its not open the Opens */
if (con.State != ConnectionState.Open)
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
/* Executing Stored Procedure */
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Te dhenat u ruajten ne databaze");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

1. You might be having more columns in your table than mentioned values(3) in your query.
so it is always good to specify the column names in your query for which columns you are inserting the values.
Try This:
INSERT INTO [TableName](COL1,COl2,COL3)
Values(Value1,Value2,Value3);
2. As you mentioned your columsn are decimals, you are inserting them as as strings by enclosing the values within single quotes.
You should not enclose the decima values within single quotes.
Suggestion : Your query is open to SQL Injection Attacks.
I Would suggest you to use the Parameterised queries to avoid them.

You are missing the fields in your insert statement.
The database will try to determine the right columns and their order, but if you don't deliver all fields in the appropriate order, your query will fail.
So in short:
Deliver all fields in the correct order;
Or: add the fields you want to fill in the insert.
Sample:
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] (Blerje, Shitje, Data) values ('" + Blerje + "','" + Shitje + "','" + Data + "')";

change the datatype to (18,6) or so, whichever is suitable for you,
The second part of decimal data type shows how many digits do you require after the 'point'. In your case it's '0', so db is rounding it to nearest integer.
Source: http://msdn.microsoft.com/en-us/library/ms187746.aspx

Related

ExecuteNonQuery() fails to operate

Simple INSERT INTO a SQL Server using a C# application. Have debugged successfully down to the line
cmd.ExecuteNonQuery();
The program doesn't err or break, but nothing happens. I've explored the possibility of a dev/production database hiccup, but that does not seem to be it.
The code below is the Save button click. The names of database objects and connection parameters DataSource Table Catalog etc. are generalized, not verbatim.
string val1 = firstTextBox.Text;
string val2 = secondTextBox.Text;
string val3 = thirdTextBox.Text;
SqlConnection conn = new SqlConnection(#"Data Source=DataSource;Initial Catalog=Catalog;User ID=username;Password=password");
string sql = "INSERT INTO dbo.Table(col1, col2, col3) VALUES (" + val1 + "," + val2 + "," + val3 + "); ";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
Thanks for any help!
If your code was copied and pasted verbatim, your connection string is not valid.
Data Source=DataSource;Initial Catalog=Catalog;User ID=username;Password=password
You need to fill in the proper values for the DataSource, InitialCatalog, UserID, and Password values.
Also the query itself would be wrong unless you actually have a table named Table.
As an aside, you also should look into (Google search for) parameterized SQL queries, as well as using statements for proper disposal of resources (a.k.a. classes that implement IDisposable).

execute sql command in asp.net

I have a problem with executing a sql command to the DB. The command should add a new user to the 'users' table.
But when I run the code, I get this Exception on:
command.ExecuteNonQuery();
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
this is the code of the page - GetSignIn.cshtml :
#{
string Uname = Request["name"];
string userName = Request["userName"];
string pass = Request["passWord"];
string pic = Request["pic"];
string privacy = Request["privacy"];
if(pic == null)
{
pic = "Shared/defaultPic.jpg";
}
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
}
What should I change in my code? Why is it happening? Where is the syntax error in the INSERT INTO?
Use parameterized queries. Here is your statement rewritten to make use of them.
I replaced your try/finally with a using block although your try/finally was acceptable.
Parameterized queries prevent errors and Sql Injection Attacks. An error could occur in your existing code if I were to submit a tick as a part of my user name or password. In the current form this would result in an exception. This is because the tick character is used to quote strings in sql syntax.
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection())
{
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (?,?,?,?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(Uname);
command.Parameters.Add(pic);
connection.Open();
command.ExecuteNonQuery();
}
}
About parameters for an OleDb connection from OleDbCommand.Parameters
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
What should I change in my code?
Change to parameters (that also fixes the problem that you don;t have quotes around the pic value)
Remove the second instance of pass in your values
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (#userName, #pass, #Uname, #pic)";
command.Parameters.Add("#userName").Value = userName;
.. etc.
It's unclear what the type if pic is - you are passing a string but I can;t tell of the column stores a file path or if you are indending to serialize the file and store it in a pinary field.
You set 4 fields after the "INTO" clause, however you're passing 5 parameters:
"INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
Just add the fifth field, or remove one parameter from the VALUES part
Please check take a look at your Insert statement, it looks like that you provided password value twice.
The number of query values and the destination fields should be same in an INSERT statement.
You have the wrong number parameters in your insert statement. For clarity, why not use string.Format to keep everything uniform? (Assuming these are all string types)
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic) VALUES ('{0}','{1}','{2}','{3}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic);
command.ExecuteNonQuery();
However, it also looks like you probably want to include that 5th parameter as well - just extend the format :
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic, privacy) VALUES ('{0}','{1}','{2}','{3}','{4}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic, privacy);
command.ExecuteNonQuery();
Since most of the answers failed to address the SQL Injection vulnerability, here's an example with parameterized queries. In addition to preventing SQL Injection attacks, it also makes it easier to troubleshoot these types of issues, and you don't need to worry about quoting or not quoting parameters.
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName, passWord, Uname, pic, privacy) VALUES (?, ?, ?, ?, ?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(name);
command.Parameters.Add(pic);
command.Parameters.Add(privacy);
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
Tnx 4 the help
It happend to be a problem with the database - you can not apply a INSERT INTO statement where the column name is "password". "password" is a Reserved word
in SQL.
Tnx again,
Etay

Problems when insert double value in MySQL

I get an error when I try to insert a double value into a table in MySQL.
I use C# to build my transactions, and ODBC drivers to connect my database to my project.
In my aspx page I make a form which permit to the user to fill severals fields and submit the values. By an Ajax call, I go in my code behind sending the form's values. And i begin my transaction.
If the user puts for instance "15.00" in the form for the double
values, the resquest is Ok and there is not problems.
But if he puts "15.65" I get an error which says that the column
count of my table doesn't match with the request column count.
However, I check the double value and it is correct. I also try to put simple quotes next to the double value, but it doesn't work.
Here is the error :
`{"Message":"[MySQL][ODBC 5.1 Driver][mysqld-5.1.73-community]Column count doesn\u0027t match value count
at row 1","StackTrace":" à ADODB.ConnectionClass.Execute(String CommandText, Object& RecordsAffected
, Int32 Options)\r\n...
Here is my resquest :
Utils.ocn.Execute("INSERT INTO datas VALUES(0,null,null,null,null,null," + RecepAccId + ",1," + CafId + ",123,null,null," + NbrKilos + ",'" + ConvertedDate + "','" + Chrono + "','" + ConvertedTimeStamp + "','" + ChronoNum + "')", out x, -1);
The severals variables provening my function's parameters
There are 17 fields in my table and I send normally 17 values in my resquests. But when I set the double with numbers after the comma, I get a bug. And according to the error message, we can suppose that, the numbers after the comma are considerated like a other field in the insert !
In doubt I put the 17 fields'names after the table name in my resquest, but I get the same result.
Have you an idea to fix it ?
To get your database driver to treat the values from the user input as individual pieces of data, you should use a parametrised query. So if your table had a single double column called, height for example.
INSERT INTO datas height
VALUES #height
Where #height is a double value parsed from the input from the request eg using double parsedHeight = double.Parse(subbmittedValue). You can then add the parameter when making your SQL command by adding:
command.Parameters.AddWithValue("#height", parsedHeight);
As #Marko Juvančič says, using string concatenation from user input to create a sql statement is dangerous. In fact, it is a major security issue leaving you open to SQL injection. Imagine a malicious user entered a SQL query to delete datas in the form. Parametrising your query as described protects you from this by preventing the user from interfering with your query.
So putting all this together, instead of executing your concatenated statement with Utils.ocn.Execute use something like:
double parsedValue = double.Parse(valueFromRequest);
//be careful, this will throw if the user didn't enter a valid double.
string connectionString = yourConnectionString;
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
connection.Open();
using (OdbcCommand command = new OdbcCommand(
"INSERT INTO datas columnName VALUES(#value)", connection))
{
command.Parameters.AddWithValue("#value", parsedValue);
command.ExecuteNonQuery();
}
}
private double failingGrade;
public double getFailingGrade()
{
using (MySqlConnection conn = new MySqlConnection(DBConnection.Connection()))
{
conn.Open();
using (MySqlCommand comm = conn.CreateCommand())
{
comm.CommandText = "select failing from gradespercentage_tab";
return failingGrade = double.Parse(comm.ExecuteScalar().ToString());
}
}
}

Casting datareader values to integer in insert statement

I am building an insert statement with data from an excel file using data reader values. The excel file datareader always only has one record. There are two columns in the destination table, first of type int and second column of varchar.
while (dr.Read())
{
string insertstring = #"insert into configtest values
('" + dr.GetValue(0) + "','"
+ dr.GetValue(1) + "')";
}
SqlCommand commandInsert = new SqlCommand(insertstring, conn);
commandInsert.ExecuteNonQuery();
I get error
"Error converting varchar type to numeric.
I tried casting the first value to type int and get a
"Specified cast is not valid"
error. Please help with this.
If the first column in the destination table is an integer column you should not pass a string.
In your concatenation command you put single quotes around the first parameter and this means you try to pass a string. Thus the error.
However you should always write a parameterized query, not try to build a sql command using string concatenation
string insertstring = #"insert into configtest values (#p1, #p2)";
while (dr.Read())
{
SqlCommand commandInsert = new SqlCommand(insertstring, conn);
if(dr.IsDBNull(0))
commandInsert.Parameters.AddWithValue("#p1", DBNull.Value);
else
commandInsert.Parameters.AddWithValue("#p1", Convert.ToInt32(dr[0]));
if(dr.IsDBNull(1))
commandInsert.Parameters.AddWithValue("#p2", DBNull.Value);
else
commandInsert.Parameters.AddWithValue("#p2", dr[1].ToString());
commandInsert.ExecuteNonQuery();
}
This approach will keep you safe from Sql Injection and from syntax error triggered if your string values contain single quotes.
As a final note, keep in mind that when a DataReader is open you cannot use its connection for other activities (ExecuteNonQuery) unless you use the MultipleActiveResultSets=True in your connection string
Replace your string with following (assuming your dr.GetValue(0) is int.)
string insertstring = #"insert into configtest values
(" + dr.GetValue(0) + ",'"
+ dr.GetValue(1) + "')";
Just removed quotes around dr.GetValue(0). As it is of type int it does not require quotes.
EDIT:
To insert null values, you can check for null values in query itself-
string insertstring = #"insert into configtest values
(" + (dr.GetValue(0) == null ? System.Data.SqlTypes.SqlInt32.Null : dr.GetValue(0)) + ",'"
+ (dr.GetValue(1) == null ? string.Empty : dr.GetValue(1)) + "')";
Though this is not the perfect solution but can do a workaround !!!!

Insert datetime from C# into SQL Server database

when I try to insert datetime value into a SQL Server database I get this error:
Conversion failed when converting date and/or time from character string
Code:
connection.Open();
SqlCommand command = new SqlCommand("insert into table values(#time)", connection);
command.Parameters.AddWithValue("#time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
Table table has 1 datetime column called time.
Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:
public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
{
int id = getMaxID() + 1;
connection.Open();
SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','#cas','" + nazev + "','" + dotaz + "')", connection);
command.Parameters.AddWithValue("#cas", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
}
The actual problem here is that you're writing the parameter inside quotes:
... ,'0','#cas',' ...
^ ^
This will not use #cas as a parameter, you're actually trying to insert the string "#cas" into that column, not the contents of the parameter #cas.
Remove the quotes and that part should work.
Additionally, don't use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the "id", "uzivatel", "nazev", and "dotav" parameters you're using (method parameters that is).
Looks like you need:
insert into table values(#time)
Without the single character quote.
Try System.Data.SqlTypes.SqlDateTime Also when storing dates please consider storing them as UTC to prevent confusion.

Categories

Resources