I've been trying to add a row to my SQL CE & nothing works I've tried many things I found here at SO or in other websites by googling but to no avail.
Below if the code I have at the moment.
It compiles and executes with no problem, but nothing is added to the table and no exception is thrown.
Could anyone please provide a solution for this ?
string conString = Properties.Settings.Default.TestConnectionString;
using (SqlCeConnection connect = new SqlCeConnection(conString))
{
connect.Open();
string text = "UsernameTest";
string pass = "PasswordTest";
using (SqlCeCommand command = new SqlCeCommand("insert into MyTable values (#Username, #Password)", connect))
{
command.Parameters.AddWithValue("#Username", text);
command.Parameters.AddWithValue("#Password", pass);
command.ExecuteNonQuery();
}
}
Please do not comment about storing a password in plain text, this was just a test.
Related
Trying to insert a new record into an MS Access .accdb file. When I run the code below, it appears to work fine. No errors are presented, but nothing updates in the database file either. I have verified that the database is in an accessible location.
selectedNote is an object with the three listed parameters. The only field I'm not including in the query string is the ID field which is autonumber.
string scon = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = |DataDirectory|AMS.accdb";
string str = "INSERT INTO Notes ([ItemID], [Note], [Note Date]) VALUES (?, ?, ?)";
try
{
using (OleDbConnection con = new OleDbConnection(scon))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("ItemID", selectedNote.ItemID);
cmd.Parameters.AddWithValue("Note", selectedNote.Note);
cmd.Parameters.AddWithValue("Note Date", selectedNote.NoteDate.ToString("dd-MM-yy"));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
Thanks all, hopefully I can get this hammered out.
EDIT: Curiously, I just found that if I hard-code a path to the .accdb file with a line like the following, it actually does write to that file. So I guess the question becomes why is it not working on the build path where the database is in the same path as the exe.
AppDomain.CurrentDomain.SetData("DataDirectory","C:\temp");
I have tried setting DataDirectory to something like AppDomain.CurrentDomain.BaseDirectory, but this doesn't seem to work either.
A date should not be inserted as text, and you do have the DateTime value, thus:
cmd.Parameters.AddWithValue("Note Date", selectedNote.NoteDate);
I get syntax error when using 'Insert into' SQL command using c#. I'm using Access db to store some data.
Surprisingly, when I copy the exact command into MS Access to try if it's not correct, it works like charm. I'm a bit confused! I appreciate any idea or help in this regard. Here is my code:
using (OleDbConnection connection = new OleDbConnection(Global.ConString))
{
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO Users(Name,UserName,Password,Customers,Jobs,Invoice,Statement,Reports,Users) values (#name,#UserName,#Password,#Customers,#Jobs,#Invoice,#Statement,#Reports,#Users)";
command.Parameters.AddWithValue("#name",fullName.Text );
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", passWord.Text);
command.Parameters.AddWithValue("#Customers", Customers.Checked);
command.Parameters.AddWithValue("#Jobs", Jobs.Checked);
command.Parameters.AddWithValue("#Invoice", Invoice.Checked);
command.Parameters.AddWithValue("#Statement", Statement.Checked);
command.Parameters.AddWithValue("#Reports", Report.Checked);
command.Parameters.AddWithValue("#Users", userDef.Checked);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
if (recordsAffected > 0)
{
foreach (Control item in newRecord.Controls)
{
if (item is TextBox) item.ResetText();
}
timer1.Enabled = true;
}
else
MessageBox.Show("Insert Fail");
}
catch (OleDbException err)
{
MessageBox.Show("Somthing wrong. Error no. is: " + err.ErrorCode + "..." + err.Message);
}
}
}
Most likely your issue is the use of a reserved word as an identifier, specifically 'Password'. Wrap that column name in brackets, i.e. [Password] and you should be good to go.
It's best to avoid reserved words if possible. Generally speaking, you should not be storing unhashed passwords in your database so a column name like 'PasswordHash` is appropriate and avoids this issue.
I am creating a login form using C# and MySQL. I got stuck in SQLConnection. It says that the keyword I used is not supported.
This is my code:
using (var con = new SqlConnection("host=localhost;usr=root;password=admin;db=timekeeping;"))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT count(*) FROM receptionist WHERE username = #username AND password = #password;";
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
var count = (long)cmd.ExecuteScalar();
return count > 0;
}
This is the screenshot of the error message:
You need to use the correct connection string keywords for MySQL:
From Connectionstrings.com:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Please change your connection string from
"host=localhost;usr=root;password=admin;db=timekeeping;"
to
"Server=127.0.0.1;Database=timekeeping;Uid=root;password=admin"
Hopefully it will work.
I am using Oracle.DataAccess.Client to work with Oracle database in my ASP.Net application. There is no help documentation in MSDN for ODP.Net and Oracle's documentation is really really bad. I am not able find the answer to this simple question.
Is it not possible to execute a simple update statement without having to build a dataset object and updating the dataset?
How to execute an update statement using Oracle ODP.Net in C#?
I will need to check the exact syntax, but here is some quick code off the top of my head
using (OracleConnection con = new OracleConnection(...))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update table set col1 = :param1, col2 = :param2 where key = :keyValue";
cmd.Parameters.AddWithValue("param1", 1);
cmd.Parameters.AddWithValue("param2", "Text data");
cmd.Parameters.AddWithValue("keyValue", "1");
cmd.ExecuteNonQuery();
}
The above creates a command object sets the command up to execute an SQL Update statement, in this example I show one way to setup a parameterized query, you should always go with a parameterized query. Once the command is setup you just call ExecuteNonQuery to actually execute the command.
So after a bit of sleuthing and working this one out for a while, I found that the method I used to add a new parameter to the connection command is as follows. I did not find the method as was stated in the previous post. Mind you I am using a query object that I am passing the values around with.
public Boolean InsertMethod(Query _query)
{
var success = false;
var queryString = string.Format(#"INSERT INTO TABLE(ID, OWNER, TEXT) VALUES (TABLE_SEQ.NEXTVAL,:OWNER, :TEXT)");
try
{
using (OracleConnection con = new OracleConnection(ConString))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = queryString;
cmd.Parameters.Add("OWNER", _query.Owner);
cmd.Parameters.Add("TEXT", _query.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated > 0) success = true;
}
return success;
}
catch (Exception ex)
{
log.Error(ex);
throw;
}
}
Further to #Chris's answer, here is the documentation page of OracleParameter class which has sample code on using OracleCommand to execute Updates.
EDIT: Here is the entry point for ODP.net documentation.
the underlying database on a project has changed from sql 2005 to MySql 5.1
The code has loads of method similar to below. I'm presuming it is just a case of switching the 'con' variable SqlConnection to a MYSql specific connection. Has anyone had any experience with this? I have never touched a mySql db. Any help much appreciated.
private SqlConnection con;
public User LogonUser(string pUserName, string pPassword)
{
con = new SqlConnection();
con.ConnectionString = DatabaseConstants.DB_CONN_STRING;
using (con)
{
con.Open();
var command = new SqlCommand();
command.Connection = con;
command.CommandText = "SELECT id FROM Users WHERE userName = #userName AND password = #password";
command.CommandType = CommandType.Text;
var userName = new SqlParameter("#userName", pUserName);
var password = new SqlParameter("#password", pPassword);
command.Parameters.Add(userName);
command.Parameters.Add(password);
User user;
var dr = command.ExecuteReader();
if (dr != null)
if (dr.HasRows)
{
while (dr.Read())
{
user = new User();
user.id = dr.GetString(0);
return user;
}
}
else
{
throw new Exception("Can not find user, please check your username and password");
}
}
return null;
}
You got it partially correct, but you will need an instance of the MySQL Provider, not the SqlConnection. Also you will have to change any SQL that isn't compatible with MySQL.
Downloadable SQL Connectors are available for various frameworks and platforms - in this case assemblies to reference into your .NET project under the guise of ADO.NET are available from MySql. Can program against them using any .NET language.
Start in C# by referencing the MySql namespace:
using MySql.Data.MySqlClient;
and change over your ADO.NET class names from SqlConnection to MySqlConnection, etc. Google Code examples show cursory usage (similar to other ADO.NET providers), and of course the MySql docs are the best reference.
No, you have to also change this line
var command = new SqlCommand();
to
var command = new con.CreateCommand();
and of course you have to change any specific T-SQL and MSSQL features to MySQL. Date and time function, stored procedure, and parameter binding(? instead of #) are a few things that you need to closely check.