I am running monodevelop on arch linux and I tried to insert some values into a local database , but when I run it from a button the application closes.The file is created and it have all fields.
Here is my code:
SqliteConnection m_dbConnection = new SqliteConnection ("Data Source=GOOD_FOOD.sqlite;Version=3;");
m_dbConnection.Open ();
int id;
string get = "SELECT LAST(id_client) FROM Clienti";
SqliteCommand comSelect = new SqliteCommand (get, m_dbConnection);
int? getid = (int?)comSelect.ExecuteScalar();
if (getid.HasValue) {
id = Convert.ToInt32(getid) + 1;
} else
{
id = 1;
}
// create account
string create = "INSERT INTO Clienti (id_client, parola, nume, prenume, adresa, email) VALUES (#id, #parola, #nume, #prenume, #adresa, #email)";
SqliteCommand createcmd = new SqliteCommand (create, m_dbConnection);
createcmd.Parameters.AddWithValue("#id", id);
createcmd.Parameters.AddWithValue ("#parola", password.Text);
createcmd.Parameters.AddWithValue("#nume", name.Text);
createcmd.Parameters.AddWithValue ("#prenume", secondname.Text);
createcmd.Parameters.AddWithValue("#adresa", address.Text);
createcmd.Parameters.AddWithValue ("#email", email.Text);
createcmd.ExecuteNonQuery ();
m_dbConnection.Close ();
The soulution :
Use try{} catch{} and change id = Convert.ToInt32(getid) + 1; to id = getid.Value +1;
Change "SELECT LAST(id_client) FROM Clienti"; to "SELECT id_client FROM Clienti ORDER BY id_client DESC;";
Related
When i use the CustomButton for to save the "Full_Name" in the Database [Rooms] => Person then there is just nothing happen. Also if i use the try & catch function, there will be no Exception.
The field in the Database stays Empty.
When i show the required variable in the MessageBox (idPlus2, Full_Name) then it throws me back the right informations.
So i think the problem must be in the UPDATE Sql string but i don't know whats wrong.
private string connstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\....mdb";
//Path anonymous
string Full_Name;
[Obsolete]
private void customButton1_Click(object sender, EventArgs e)
{
conn = new OleDbConnection(connstr);
conn.Open();
strSQL = "SELECT * FROM [Guests] WHERE ID = ?";
cmd = new OleDbCommand(strSQL, conn);
da = new OleDbDataAdapter(cmd);
int id = CustomComboBox1.SelectedIndex;
int idPlus = id + 1;
cmd.Parameters.Add("?", idPlus);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Full_Name = reader["Vorname"].ToString() + ' ' + reader["Nachname"].ToString();
}
reader.Close();
string insertQuery = #"UPDATE [Rooms] SET Person = #Full_Name WHERE ID = ?";
cmd = new OleDbCommand(insertQuery, conn);
int id2 = customComboBox2.SelectedIndex;
int idPlus2 = id2 + 2;
cmd.Parameters.Add("?", idPlus2);
cmd.Parameters.Add(new OleDbParameter("#Full_Name", Full_Name));
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
LoadTheme();
}
I have the answer
cmd.Parameters.Add("?", OleDbType.VarChar, 255).Value = CustomComboBox1.Texts;
cmd.Parameters.Add("?", idPlus2);
With OleDb you have to use ? for each variable or object which should be added to the database. That means that you can't specify the variable by name in the SQL string. You have to use the same order as the SQL string in C # code to insert the parameters.
This is my CustomerRegister class, but I cant seem to input data from my addressTextBox into the CustomerTbl.
DataBase dbObj = new DataBase();
string selStr = "Update CustomerTbl Set customer_address = '" + addressTextBox.Text + "' Where custID = " + "NULL";
int i = dbObj.ExecuteNonQuery(selStr);
This is my DataBase class but return comdObj.ExecuteNonQuery(); doesnt work as there is not such custID named NULL. So how do i program in such a way so that i am able to constantly update the database when a new user registers?
class DataBase
{
string connStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\OOPG\Banking Mini Project Raynard\Banking Mini Project Raynard\Database1.mdf;Integrated Security = True";
SqlConnection connObj;
SqlCommand comdObj;
SqlDataReader dR;
public DataBase()
{
connObj = new SqlConnection(connStr);
connObj.Open();
}
public SqlDataReader ExecuteReader(string selStr)
{
comdObj = new SqlCommand(selStr, connObj);
dR = comdObj.ExecuteReader();
return dR;
}
public int ExecuteNonQuery(string sqlStr)
{
comdObj = new SqlCommand(sqlStr, connObj);
return comdObj.ExecuteNonQuery();
}
}
First you should create a connection to SQL database before executing any query. After then you should be able to insert data before updating any data into database. After you insert data successfully you can update data using above command text. Here is some sample code for inserting data for registering customer.
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection; // <== lacking
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into CustomerTbl (CustId, Name, Address) VALUES (#CustId, #Name, #Address)";
command.Parameters.AddWithValue("#CustId", name);
command.Parameters.AddWithValue("#Name", userId);
command.Parameters.AddWithValue("#Address", idDepart);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close();
}
}
If you're adding a record, you're going to need to INSERT, not UPDATE. For example (here using "Dapper" to do all the heavy work, including parameter handling):
using Dapper;
//...
void UpsertAddress(int? id, string address)
{
if (id is null)
{
connection.Execute("insert CustomerTbl (customer_address) values (#address);",
new { address }); // possibly using the OUTPUT clause to fetch an IDENTITY
}
else
{
connection.Execute(
"update CustomerTbl set customer_address = #address where custID = #id;",
new { id, address });
}
}
ionline - class, string myname
private static void SetOnlineStatus(PacketHeader header, Connection connection, ionline message)
{
Console.WriteLine("Check online: " + message.myname);
MySqlCommand mycmd = new MySqlCommand();
mycmd.CommandText = "SELECT * FROM users WHERE username = ?user";
mycmd.Connection = mconnection;
mycmd.Parameters.AddWithValue("user", message.myname);
MySqlDataReader Reader = mycmd.ExecuteReader();
while (Reader.Read())
{
Console.WriteLine("Check online: " + message.myname+" "+GetDBString("username",Reader));
MySqlCommand mycmd2 = new MySqlCommand();
mycmd2.CommandText = "UPDATE users SET online = 0 WHERE userid = #user2";
mycmd2.Parameters.AddWithValue("#user2", Reader.GetInt32("userid"));
mycmd2.Connection = mconnection;
Console.WriteLine(mycmd2.ExecuteNonQuery().ToString());
}
}
Mysql request "mycmd2" isn't executed . What in my query not the correct?
While a DataReader is open its connection is busy serving the reader.
The connection cannot be used to make other operations on the database.
You should get an exception though.
If your first query returns zero or one row, then you could simplify your code using the ExecuteScalar method and removing the need to use a MySqlDataReader
Console.WriteLine("Check online: " + message.myname);
MySqlCommand mycmd = new MySqlCommand();
mycmd.CommandText = "SELECT userid FROM users WHERE username = ?user";
mycmd.Connection = mconnection;
mycmd.Parameters.AddWithValue("user", message.myname);
object result = mycmd.ExecuteScalar();
if(result != null)
{
int userID = Convert.ToInt32(result);
MySqlCommand mycmd2 = new MySqlCommand();
mycmd2.CommandText = "UPDATE users SET online = 0 WHERE userid = #user2";
mycmd2.Parameters.AddWithValue("#user2", userID);
mycmd2.Connection = mconnection;
mycmd2.ExecuteNonQuery();
}
I am working for CSV File import to SQL Server
I got code from Internet ..working fine But when I am adding one extra field (User_Id) with that CSV file to SQL then this is giving error ....I am not able to understand where is doing mistake ....code...
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("Name");
tblReadCSV.Columns.Add("Email");
tblReadCSV.Columns.Add("Mobile");
tblReadCSV.Columns.Add("User_id");
string path = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Email/UploadFile/" + path));
path = Server.MapPath("~/Email/UploadFile/" + path);
TextFieldParser csvParser = new TextFieldParser(path);
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true))
{
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
string strCon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(#Name,#Email,#Mobile," + UserId +")";
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 50, "Name");
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 50, "Email");
cmd.Parameters.Add("#Mobile", SqlDbType.VarChar, 50, "Mobile");
cmd.Parameters.Add("#User_id", SqlDbType.Int , UserId);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
Label1.Text = "File successfully uploaded";
You don't say what the error message is, nor where it occurs, but it seems to me that this line
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(#Name,#Email,#Mobile," + UserId +")";
should probably be like this
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(#Name,#Email,#Mobile,#User_id)";
Replace
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id)
values(#Name,#Email,#Mobile," + UserId +")";
with
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id )
values(#Name,#Email,#Mobile,#UserId)";
In the above line, you are just declaring the parameters .
And this is how you actually pass the current user id:
cmd.Parameters.Add("#User_id", SqlDbType.Int , UserId);
Try this; hope it will work.
values(#Name,#Email,#Mobile," + UserId +")"// source from ur c
avoid ''+ UserId +'' in your string strSql..
I've been trawling through pages and pages on the internet for days now trying different approaches and I'm still not sure how I should be doing this.
On my third InsertCommand, I'd like to reference a column on the other 2 tables.
// Populate a DataSet from multiple Tables... Works fine
sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("SELECT * FROM hardware", sqlConn);
sqlDA.Fill(ds, "Hardware");
sqlDA.SelectCommand.CommandText = "SELECT * FROM software";
sqlDA.Fill(ds, "Software");
sqlDA.SelectCommand.CommandText = "SELECT * FROM join_hardware_software";
sqlDA.Fill(ds, "HS Join");
// After DataSet has been changed, perform an Insert on relevant tables...
updatedDs = ds.GetChanges();
SqlCommand DAInsertCommand = new SqlCommand();
DAInsertCommand.CommandText = "INSERT INTO hardware (host, model, serial) VALUES (#host, #model, #serial)";
DAInsertCommand.Parameters.AddWithValue("#host", null).SourceColumn = "host";
DAInsertCommand.Parameters.AddWithValue("#model", null).SourceColumn = "model";
DAInsertCommand.Parameters.AddWithValue("#serial", null).SourceColumn = "serial";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Hardware"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO software (description) VALUES (#software)";
DAInsertCommand.Parameters.AddWithValue("#software", null).SourceColumn = "description";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Software"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO join_hardware_software (hardware_id, software_id) VALUES (#hardware_id, #software_id)";
// *****
DAInsertCommand.Parameters.AddWithValue("#hardware_id", null).SourceColumn = "?"; // I want to set this to be set to my 'hardware' table to the 'id' column.
DAInsertCommand.Parameters.AddWithValue("#software_id", null).SourceColumn = "?"; // I want to set this to be set to my 'software' table to the 'id' column.
// *****
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "HS Join");
Could somebody please tell me where I am going wrong and how I could potentially overcome this? Many thanks! :)
With regards to your comments this seems to be one of those occasions where if you and I were sat next to each other we'd get this sorted but it's a bit tricky.
This is code I've used when working with SqlConnection and SqlCommand. There might be stuff here that would help you.
public static void RunSqlCommandText(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
}
public static int RunSqlAndReturnId(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
int id = -1;
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
var returnvalue = comm.ExecuteScalar();
if (returnvalue != null) {
id = (int)returnvalue;
}
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
return id;
}