I try to insert some data in an Acces database using Parameters.AddWithValue
but the result is that there is an error in the insert clause
private const string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\andres\" +
#"Documents\synchro.accdb";
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection(conString);
OleDbCommand cmd;
public void setData(string temperature, string humidity,int month,int day,int year,string session)
{
//SQL STMT
const string sql = "INSERT INTO termohigrometer(temperature,humidity,month,day,year,session) VALUES(#TEMPERATURE,#HUMIDITY,#MONTH,#DAY,#YEAR,#SESSION)";
cmd = new OleDbCommand(sql, conn);
Console.Write("temperatura "+temperature);
cmd.Parameters.AddWithValue("#TEMPERATURE", temperature);
cmd.Parameters.AddWithValue("#HUMIDITY", humidity);
cmd.Parameters.AddWithValue("#MONTH", month);
cmd.Parameters.AddWithValue("#DAY", day);
cmd.Parameters.AddWithValue("#YEAR", year);
cmd.Parameters.AddWithValue("#SESSION", session);
Console.Write("query " +cmd.CommandText );
try
{
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show(#"Successfully Inserted");
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
this is the result of the cmd.CommandText
INSERT INTO termohigrometer(temperature,humidity,month,day,year,session)
VALUES(#TEMPERATURE,#HUMIDITY,#MONTH,#DAY,#YEAR,#SESSION)
This is the exception message
These words month,day,year,session are reserved words for MS-Access. If you have fields with these names I strongly suggest you to change them to something different. Otherwise you need to put square brackets around them to avoid confusing the Jet Sql Engine.
const string sql = #"INSERT INTO termohigrometer
(temperature,humidity,[month],[day],[year],[session])
VALUES(#TEMPERATURE,#HUMIDITY,#MONTH,#DAY,#YEAR,#SESSION)";
Consider also to replace the AddWithValue method with the more precise Add method with a datatype for the parameter
cmd.Parameters.Add("#TEMPERATURE", OleDbType.VarWChar).Value = temperature;
....
Read this well known post about the dangers inside this 'convenient' method.
Can we stop using AddWithValue already?
Related
I'm working on Form that sends about 9 fields to my SQL ACCESS database and i got this error.
"Data type mismatch in criteria expression."
i'm sure it's something with the ' x ' i put in my query but still can't figure out what is THE problem.
it's (int,int,string,string,string,int,int,string,int,int) format
string SqlStr = string.Format("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values({0},{1},'{2}','{3}','{4}',{5},{6},'{7}',{8},{9})", s.ClientId,s.OrderId,s.Date,s.CardTyp,s.PayMethod,s.Ex_Y,s.Ex_M,s.CcComp,s.CcNum,s.TotalSale);
Thanks for your help.
String.Format will not be a good approach for building queries. I suggest you to use, Parameterised queries that helps you to specify the type too and also its more helpful to prevent injection: Here is an example for you:
string query = "insert into Orders" +
"(client_id,order_id,date_,card_typ,...)" +
" values(#client_id,#order_id,#date_,#card_typ...)";
using (SqlCommand sqCmd = new SqlCommand(query, con))
{
con.Open();
sqCmd.Parameters.Add("#client_id", SqlDbType.Int).Value = s.ClientId;
sqCmd.Parameters.Add("#order_id", SqlDbType.VarChar).Value = s.OrderId;
sqCmd.Parameters.Add("#date_", SqlDbType.DateTime).Value = s.Date;
sqCmd.Parameters.Add("#card_typ", SqlDbType.Bit).Value = s.CardTyp;
// add rest of parameters
//Execute the commands here
}
Note: I have included only few columns in the example, you can replace ... with rest of columns.
Please dont use a concatenation string ...
Here is an example :
using (SqlConnection connection = new SqlConnection("...connection string ..."))
{
SqlCommand command = new SqlCommand("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values(#client_id,#order_id,#date_,#card_typ,#pay_mthd,#ex_y,#ex_m,#cc_comp,#cc_num,#t_sale)", connection);
SqlParameter pclient_id = new SqlParameter("#client_id", System.Data.SqlDbType.Int);
pclient_id.Value = 12;
command.Parameters.Add(pclient_id);
SqlParameter pcard_typ = new SqlParameter("#card_typ", System.Data.SqlDbType.VarChar);
pcard_typ.Value = "some value";
command.Parameters.Add(pcard_typ);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}
After spending several hours i am unable to figure out that why null values are being inserted into mySQL table using ASP.NET web page. I am using odbc connector for this.Below is the code for the same.
public int Insert(string FirstName, string LastName, int age)
{
OdbcConnection conn = new OdbcConnection(connStr);
conn.Open();
OdbcCommand odcmd_Insert = new OdbcCommand("INSERT INTO webuse(firstName,lastName,age) VALUES(#param1,#param2,#param3)",conn);
odcmd_Insert.Connection = conn;
odcmd_Insert.CommandType = System.Data.CommandType.Text;
try
{
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param1", FirstName));
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param2", LastName));
odcmd_Insert.Parameters.Add( new OdbcParameter("#param3", age));
return odcmd_Insert.ExecuteNonQuery();
}
catch (OdbcException e)
{
throw;
}
finally {
odcmd_Insert.Dispose();
conn.Close();
conn.Dispose();
}
}
I have debugged the code and all things seems well but all columns are updated with null values. Please help i am a noob to ASP.NET.
Please try your argument like as below. I have used the MySqlConnection. you can use ODBC connection as well.
try
{
// Connection string for a typical local MySQL installation
string cnnString = "Server=localhost;Port=3306;Database=ci_series;Uid=root;Pwd=";
// Create a connection object
MySqlConnection connection = new MySqlConnection(cnnString);
// Create a SQL command object
string cmdText = "INSERT INTO webuse(firstName,lastName,age) VALUES(?param1,?param2,?param3)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("?param1", MySqlDbType.VarChar).Value = firstName;
cmd.Parameters.Add("?param2", MySqlDbType.VarChar).Value = lastName;
cmd.Parameters.Add("?param3", MySqlDbType.VarChar).Value = age;
connection.Open();
int result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
The command should be as
string cmdText = "INSERT INTO webuse(firstName,lastName,age) VALUES(?param1,?param2,?param3)";
I think that your OdbcCommand should be (replace in query #paramN with ?)
OdbcCommand odcmd_Insert = new OdbcCommand("INSERT INTO webuse(firstName,lastName,age) VALUES(?,?,?)",conn);
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param1", FirstName));
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param2", LastName));
odcmd_Insert.Parameters.Add( new OdbcParameter("#param3", age));
Instead of the parameter it takes a ? in the CommandText (leave the name in the actual parameters param1,param2,param3)
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'm very new to C#. I'm trying to retrieve the number of columns using:
SELECT count(*) FROM sys.columns
Could you please explain how to use the command and put it into a variable.
To connect to the database you can use the SqlConnection class and then to retrieve the Row Count you can use the Execute Scalar function. An example from MSDN:
cmd.CommandText = "SELECT count(*) FROM sys.columns;";
Int32 count = (Int32) cmd.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection
You will need to use ExecuteScalar as the others have said. Also, you will need to filter your SELECT on the object_id column to get the columns in a particular table.
SELECT count(*) FROM sys.columns WHERE object_id = OBJECT_ID(N'table_name')
Alternatively, you could do worse than familiarise yourself with the ANSI-standard INFORMATION_SCHEMA views to find the same information in a future-proof, cross-RDBMS way.
You have to use a command and retrieve back the scalar variable :
SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT Count(*) from sys.columns";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}",
reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
use Executescalar() for getting a single element.
using (SqlConnection con = new SqlConnection(ConnectionString)) //for connecting to database
{
con.Open();
try
{
using (SqlCommand getchild = new SqlCommand("select count(*) from table1 ", con)) //SQL queries
{
Int32 count = (Int32)getchild.ExecuteScalar();
}
}
}
Use ExecuteScalar
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Int32 colnumber = 0;
string sql = "SELECT count(*) FROM sys.columns";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
colnumber = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You'll want to use the ADO .NET functions in the System.Data.SqlClient namespace. ExecuteScalar is an easy-to-use method when you only want to get a single result. For multiple results, you can use a SqlDataReader.
using System.Data.SqlClient;
string resultVar = String.Empty;
string ServerName="localhost";
string DatabaseName="foo";
SqlConnection conn=new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI",ServerName,DatabaseName));
SqlCommand cmd=new SqlCommand(Query,conn);
try
{
conn.Open();
}
catch (SqlException se)
{
throw new InvalidOperationException(String.Format(
"Connection error: {0} Num:{1} State:{2}",
se.Message,se.Number, se.State));
}
resultVar = (string)cmd.ExecuteScalar().ToString();
conn.Close();
I'm trying to add a record but I get an exception. Any ideas?
private void Form1_Load(object sender, EventArgs e)
{
string _connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
string _query = "INSERT INTO Table1 VALUES ('MS','AH','BOSS')";
DataSet _ds = new DataSet();
try
{
using (SqlConnection _conn = new SqlConnection(_connStr))
{
SqlDataAdapter _da = new SqlDataAdapter(_query, _conn);
_conn.Open();
_da.Fill(_ds);
}
// insert null dataset or invalid return logic (too many tables, too few columns/rows, etc here.
if (_ds.Tables.Count == 1)
{ //There is a table, assign the name to it.
MessageBox.Show("1");
_ds.Tables[0].TableName = "Table1";
}
//Then work with your tblWorkers
MessageBox.Show(_ds.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Console.Write("An error occurred: {0}", ex.Message);
}
}
how can i add a record to the table?? data type is nchar
Try this:
string _connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
string _query = "INSERT INTO Table1 VALUES ('MS','AH','BOSS')";
using (SqlConnection _conn = new SqlConnection(_connStr))
{
SqlCommand _com = _conn.CreateCommand();
_conn.Open();
_com.CommandText = _query;
_com.ExecuteNonQuery();
}
In general:
SqlDataAdapter (and DataSet.Fill method) are used for reading data in first turn (and update loaded data set in case you change it). Read MSDN on this subject
SqlCommand is used for executing sql queries
additionally your INSERT command will only work if you have 3 fields in your table. If you have more than three fields you need to explicitly declare which three fields you want to insert those values into.
INSERT INTO TableName (Field1, Field2, Field3) VALUES ('MS','AH','BOSS')