So I'm receiving this problem, I tried everything. Kinda stuck
My access database design:
ID - AutoNumber
Data - ShortText
And the insert command:
OleDbCommand command = new OleDbCommand();
string sql = "INSERT INTO Table (Data) VALUES (#Data)";
OleDbCommand cmd = new OleDbCommand(sql, connection);
cmd.Parameters.AddWithValue("#Data", "Test");
connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("err: " + ex);
throw;
}
connection.Close();
This might be dumb but I'm really lost and I have no idea what to do.
The TABLE is a reserved keyword so you should change it's name or you should enclose it in square brackets like [Table]:
string sql = "INSERT INTO [Table] (Data) VALUES (#Data)";
Related
I'm trying to add something so that things can be deleted from a table, though it says there is a syntax error near '=' and I can't seem to spot it. I know this isn't the most ideal way to be doing this, but I've been told to do it this way.
Here's what I've put:
Con.Open();
string query = "DELETE FROM tablepassengers WHERE passportno.=" + tbpassno.Text + ';';
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
Con.Close();
populate();
As you said the . is meant to be there and that the column name is passportno., this is where your problem is. It's not something that is expected, or recommended, but it is something that can be handled.
When using Sql you really should be using Parameters when constructing Sql statements in code. It is strongly suggested, not only is it good practice it will protect your applications from targetted attacks, to use Parameters -- Please read Why do we always prefer using parameters in SQL statements?
Change your code to look like this:
string query = "DELETE FROM tablepassengers WHERE [passportno.]=#passportNo;";
using (SqlCommand cmd = new SqlCommand(query, Con))
{
cmd.Parameters.Add(new SqlParameter("passportNo", SqlDbType.VarChar, 100).Value = tbpassno.Text;
cmd.ExecuteNonQuery();
}
MessageBox.Show("deleted");
Con.Close();
try
{
string query = "DELETE FROM tablepassengers WHERE passportno=" + tbpassno.Text;
SqlCommand cmd = new SqlCommand(query, Con);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
}
catch (SqlException ex)
{
MessageBox.Show("Error\n" + ex.Message);
}
finally
{
Con.Close();
}
I want creating stored procedures in MySql using the OdbcCommand class.
After the stored procedure is named, I define one OdbcCommand parameter for every parameter in the stored procedure.
IN parameters are defined with the parameter name and the object containing the value, OUT parameters are defined with the parameter name and the data type that is expected to be returned.
All parameters need the parameter direction defined.
The following C# code it's my test.
The SP it's created correctly but I have error on
ERROR [42000] [MySQL][ODBC 5.1 Driver][mysqld-5.1.51-community] 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
'add_emp' at line 1
On this part of C# code
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "add_emp;";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#tname", "Jones");
cmd.Parameters["#tname"].Direction = ParameterDirection.Input;
cmd.Parameters.Add("#empno", OdbcType.Int);
cmd.Parameters["#empno"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery(); <<< Line of error
Response.Write("Employee exists: " + cmd.Parameters["#empno"].Value);
}
catch (Exception ex)
{
throw ex;
}
Any suggestion?
using (OdbcConnection conn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
OdbcCommand cmd = new OdbcCommand();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "DROP PROCEDURE IF EXISTS add_emp";
cmd.ExecuteNonQuery();
cmd.CommandText = "CREATE PROCEDURE add_emp(" +
"IN tname VARCHAR(255), OUT empno INT)" +
"BEGIN SELECT EXISTS( SELECT empo FROM do_table WHERE name = tname ) INTO #titem_id; " +
"SET empno = #titem_id; END";
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
conn.Close();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "add_emp;";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#tname", "Jones");
cmd.Parameters["#tname"].Direction = ParameterDirection.Input;
cmd.Parameters.Add("#empno", OdbcType.Int);
cmd.Parameters["#empno"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
Response.Write("Employee exists: " + cmd.Parameters["#empno"].Value);
}
catch (Exception ex)
{
throw ex;
}
conn.Close();
}
I am writing a sample application to insert data into a SQL Server database using C#. Data is not persisting in the database.
Below is my code:
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Insert into Record (ID,Name) values ('" + txtId.Text + "' , '" + txtName.Text + "')";
cmd.ExecuteNonQuery();
//cmd.Clone();
conn.Close();
The values are not persisted. There is no error when I insert the values. When I changed my command to:
"Insert into Database.dbo.Record (ID,Name) values ('"
it throws an exception:
Incorrect syntax near the keyword 'Database'.
Why is my SQL Server database not being updated?
Your code as is, is possibly open to SQL injection - you should use parameters.
Also check the table names and primary keys, e.g. if ID is an Identity column it is automatically generated when you insert, so then you'll just INSERT INTO Record (Name) VALUES ('Bob')
Otherwise if ID is a primary key you'll likely have to check you are not trying to insert duplicates.
Please use parameters! (adjust the SqlDbType's if needed)
You should also use a using statement over the connection to properly dispose resources, and ideally use a transaction for updates:
string sqlQuery = "INSERT INTO Record (ID, Name) VALUES (#id, #name); ";
using (SqlConnection conn = new SqlConnection(connectionString)) {
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try {
SqlCommand command = new SqlCommand(sqlQuery, conn, tran);
SqlParameter in1 = command.Parameters.Add("#id", SqlDbType.NVarChar);
in1.Value = txtId.Text;
SqlParameter in2 = command.Parameters.Add("#name", SqlDbType.NVarChar);
in1.Value = txtName.Text;
command.ExecuteNonQuery();
tran.Commit();
} catch (Exception ex) {
tran.Rollback();
//...
}
}
I am developing a system that heavily relies on emailing, I'm trying to determine if users wanted to get notified or not.
User details are stored in SQL Server Express. I want to check which registered users wanted to receive and get their emails from the database. Is this possible?
So far I got this far:
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT COUNT(*) FROM [UserTable] WHERE ([price] = #price)";
command.Parameters.AddWithValue("#price", "10.000");
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show("Error is SQL DB: " + ex);
}
finally
{
connection.Close();
}
}
It returns -1, but I have a 10.000 in one row. And from here I want to save the email addresses of those who has 10.000 on their preferences from the db so I can add it to email list.
So to summarize: Check all rows if some of them has 'yes' and save their 'email' from the same row.
Can someone point me to the right direction? Thank you.
Updated it for #SeM
private void getMailList()
{
using (SqlConnection connection = new SqlConnection("Data Source=DESKTOP-9MMTAI1\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
{
try
{
connection.Open();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(*) FROM UserTable WHERE price = #price";
cmd.Parameters.Add(new SqlParameter("#price", 10000));
int count = int.Parse(cmd.ExecuteScalar());
}
}
catch (Exception ex)
{
MessageBox.Show("Error is SQL DB: " + ex);
//Handle your exception;
}
}
}
ExecuteNonQuery returning the number of rows that affected only for Update, Insert and Delete statements. In your case, you will always get get -1, because on Select statement ExecuteNonQuery returning -1
So try this:
using(SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
using(SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(*) FROM UserTable WHERE price = #price";
cmd.Parameters.Add(new SqlParameter("#price", 10000));
int count = int.Parse(cmd.ExecuteScalar());
}
}
catch (Exception ex)
{
//Handle your exception;
}
}
As commented above, ExecuteNonQuery does just that - no query results.
Instead:
int recordsAffected = (int)command.ExecuteScalar();
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
using (var conexao = Conexao())
{
conexao.Open();
string rotaloja = Convert.ToString(dtExcel.Rows[i][1]) + Convert.ToString(dtExcel.Rows[i][0]);
string bn = "select * from Emb where ROTALOJ= #rotaloja";
OleDbCommand cmd1 = new OleDbCommand(bn, conexao);
cmd1.Parameters.AddWithValue("#rotaloja", rotaloja);
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
using (OleDbDataReader drr = Queryyy.ExecuteReader())
{
if (drr.Read())
{
try
{
string cmdText = "UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja";
conexao.Open();
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
try
{
string cmdText = "INSERT INTO Emb (ROTALOJ , ROTA, LOJA, QTDEEMBAL) VALUES (#rotaloja,#p0,#p1,#p2)";
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
//////////////////////////////////////////////////////////////////////////////////////////////
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
}
}
I am doing import excel to database more when he does select to see if you have the information in the database is giving error can be? for those who help me thank you
Img : http://i.stack.imgur.com/qxQDm.png
You created a new query Queryyy and assumed that the parameters attached with previous query cmd1 would be available with your command string bn. You need to add parameter to your query Queryyy
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
Query.Parameters.AddWithValue("#rotaloja", rotaloja); //here
using (OleDbDataReader drr = Queryyy.ExecuteReader())
//.......rest of your code
}
Consider using helpful variable names.
In your current code, you added parameter to a cmd1 which is independent of Queryyy. In your new query Queryyy, you are using command text which requires a parameter and since you are not passing it, you are getting the exception.
Take a look at : OleDbCommand.Parameters Property, You may have to pass the parameter with ?, since it doesn't seem to support named parameters.
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.
You're not setting the value of #rotaloja in this query:
"UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja"
OleDBCommand does not support names parameters. Replace your parameters with ? in each SQL statement and add the parameters in the order that they appear in the query.