I need to insert a new row in a mysql table using C#.
The table looks like this, and contains one foreign key column.
i use the follwing code to cinnect to the database and insert data.
public virtual void addToDB()
{
try
{
//prepare for query
var cmd = MySQL.readyQuery();
//insert testdata to Vo2test
cmd.CommandText = "INSERT INTO vo2test_tb(ClientID, Weight, Methods, TimeOfDay, Date, StartResistance, Endresistance, TheoreticalMaxPulse, FatPercent3point, FatPercent7point, VO2_max, FitnessRating, HRmax, RERmax, TestTime, Raw_test_data) VALUES((SELECT UserID from user_tb WHERE UserID = '#UserID'), '#Weight', '#Method', '#Timeofday', '#Date', '#Startresistance', '#Endresistance', '#Theoreticalmaxpulse', '#Fatprocent3p', '#Fatprocent7p', '#vo2max', '#fitnessrating', '#hrmax', '#rermax', '#testtime', '#rawtestdata')";
cmd.Prepare();
//insert parameters som skal ændres:
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#Weight", Weight);
cmd.Parameters.AddWithValue("#Method", Method);
//coverts date to 0000-00-00
string DateString = Convert.ToString(TestDate.Date.Date.Year) + "-" + Convert.ToString(TestDate.Date.Month) + "-" + Convert.ToString(TestDate.Date.Day);
cmd.Parameters.AddWithValue("#Date", DateString);
//converts time to 00:00:00.
string TimeString = Convert.ToString(TimeOfDay.Hour) + ":" + Convert.ToString(TimeOfDay.Minute) + ":00";
cmd.Parameters.AddWithValue("#Timeofday", TimeString);
cmd.Parameters.AddWithValue("#Startresisstance", StartResistance);
cmd.Parameters.AddWithValue("#Endressistance", EndResistance);
cmd.Parameters.AddWithValue("#TheoreticalMaxPulse", TheoreticMaxPulse);
cmd.Parameters.AddWithValue("#FatPercent3point", FatPercent3Point);
cmd.Parameters.AddWithValue("#FatPercent7point", FatPercent7Point);
cmd.Parameters.AddWithValue("#VO2_max", Vo2Max);
cmd.Parameters.AddWithValue("#FitnessRating", FitnessRating);
cmd.Parameters.AddWithValue("#HRmax", HRmax);
cmd.Parameters.AddWithValue("#RERmax", RERmax);
cmd.Parameters.AddWithValue("#TestTime", TimeOfDay);
cmd.Parameters.AddWithValue("#Raw_test_data", RawTestData);
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
}
}
when i run it, i am told that ClientID can't be null but if i just run the sql query in Adminer it works fine.
The sub select in your insert query doesnt make sense. Why are you doing a sub select to insert a value you already have.
SELECT UserID from user_tb WHERE UserID = '#UserID'
Just insert #UserID directly.
Also you have wrapped all your # parameters in single quotes in the query string. You do not need this. Parameterization deals with the quotes for you in the background. Remove all single quotes so that it just reads:
cmd.CommandText = "INSERT INTO vo2test_tb(ClientID, Weight, Methods, TimeOfDay, Date,
StartResistance, Endresistance, TheoreticalMaxPulse, FatPercent3point, FatPercent7point,
VO2_max, FitnessRating, HRmax, RERmax, TestTime, Raw_test_data)
VALUES((SELECT ClientID from user_tb WHERE UserID = #UserID), #Weight, #Method, #Timeofday,
#Date, #Startresistance, #Endresistance, #Theoreticalmaxpulse, #Fatprocent3p, #Fatprocent7p,
#vo2max, #fitnessrating, #hrmax, #rermax, #testtime, #rawtestdata)";
Related
String insertUser = "Insert into
Users(FirstName,LastName,EmailAddress,Password,BirthDate,PhoneNumber)"
+ "values('#first','#last','#ema','#pass','#bid','#num');";
SqlCommand addUser = new SqlCommand(insertUser,scn);
addUser.Parameters.Clear();
addUser.Parameters.AddWithValue("#first", FirstNameTextbox.Text);
addUser.Parameters.AddWithValue("#last", LastNameTextbox.Text);
addUser.Parameters.AddWithValue("#ema", EmailTextbox.Text);
addUser.Parameters.AddWithValue("#pass", PasswordTextbox.Text);
addUser.Parameters.AddWithValue("#bid", BirthDateDateTimePicker.Value);
addUser.Parameters.AddWithValue("#num", PhoneNumberTextbox.Text);
addUser.ExecuteNonQuery();
When i execute this i get the exception in the title . How can it be fixed ?
Based on your description, you want to insert datetimepicker.value into database.
I recommend that you remove single quotes for insertion parameters.
Besides, you need to set the BirthDate column to date type.
Code:
string insertUser = "Insert into Users(FirstName, LastName, EmailAddress, Password, BirthDate, PhoneNumber)"
+ "values(#first,#last,#ema,#pass,#bid,#num);";
SqlCommand addUser = new SqlCommand(insertUser, scn);
addUser.Parameters.Clear();
addUser.Parameters.AddWithValue("#first", FirstNameTextbox.Text);
addUser.Parameters.AddWithValue("#last", LastNameTextbox.Text);
addUser.Parameters.AddWithValue("#ema", EmailTextbox.Text);
addUser.Parameters.AddWithValue("#pass", PasswordTextbox.Text);
addUser.Parameters.AddWithValue("#bid", BirthDateDateTimePicker.Value.ToString("yyyy-MM-dd"));
addUser.Parameters.AddWithValue("#num", PhoneNumberTextbox.Text);
addUser.ExecuteNonQuery();
MessageBox.Show("Data inserted successfully");
Result:
I am creating a project on courier service. I got this error when I tried to enter values at run time. I have 2 insert statements, one for the sender and the other for Receiver. But the problem exists in insert statement for Sender and in LoginID. Actually, I want to add the logged user in "Sender" Table, so that I can see, how much entries, the logged user did. First, I am getting LoginID from the "Login" table using this statement
log_id = Convert.ToInt32(dt.Rows[0][0]);
Where log_id is an integer variable. And dt is a data table name
It works perfectly. I have seen it by using messagebox.
And then I created a Public Variable to use it on other forms.
public int logId
{
get { return log_id; }
}
Then I called this variable on my data entry form like this.
public StdExpIntl(int logId)
{
InitializeComponent();
logID = logId;
}
And this is my Insert Statement
Insert into Sender(CourierNo,LoginID,SenderName) values ('" + cNo.Text + "','"+logID+"', '" + Name1.Text + "')", con);
This is not the full statement, but I guess it is ok for now.
Login table
LoginID numeric(18, 0) NOT NULL
StaffID varchar(15) NOT NULL
username varchar(10) NOT NULL
password varchar(10) NOT NULL
Sender Table
CourierNo varchar(15) NOT NULL
LoginID numeric(18, 0) NOT NULL
SenderName text NOT NULL
SenderNIC numeric(18, 0) NOT NULL
SenderCountry text NOT NULL
SenderState text NOT NULL
The error is in LoginID, please someone help me.
I see the following:
the insert statement uses single quotation around each parameter to insert, including LogID. Since LogID is numeric, it would not need this, so your insert statement should look like this:
Insert into Sender(CourierNo,LoginID,SenderName) values ('" + cNo.Text + "',"+logID+", '" + Name1.Text + "');
to prevent micro-managing your queries in such a way, you can make use of parameterizing your queries.
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand("Insert into Sender(CourierNo,LoginID,SenderName) values (#courierNo, #loginId, #senderName)",connection))
{
command.Parameters.Add(new SqlParameter("courierNo", cNo.Text));
command.Parameters.Add(new SqlParameter("loginId", logID));
command.Parameters.Add(new SqlParameter("senderName", Name1.Text));
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
You're setting a variable to itself.
public StdExpIntl(int logId)
{
InitializeComponent();
logID = logId;
}
You want...
public StdExpIntl(int logId)
{
InitializeComponent();
log_id = logId;
}
Try
Insert into Sender(CourierNo,LoginID,SenderName) values
('" + cNo.Text + "'," + logID + ", '" + Name1.Text + "')", con);
I have removed single quote around logID
I am updating a database with a new registered user. they will then be given a userid. I want to use that number when updating there location in another table. but i dont know what the user id will be. (it is autoincrement number) So i was thinkning i would update the first table. And then select the maximum user id and insert that id as the location user id in the other table but I cant get it to work.
Here is the code.
String StrSQL = "INSERT INTO Fastelejer (Fornavn,Efternavn) VALUES ('" + fornavn + "','" +
Efternavn + "')";
OleDbCommand InsertCommand = new OleDbCommand(StrSQL, conn);
InsertCommand.ExecuteNonQuery();
StrSQL = "INSERT INTO Bådpladser (Fastelejerid) SELECT MAX (Fastelejerid) FROM
StrSQL = "INSERT INTO Bådpladser (Fastelejerid) SELECT MAX (Fastelejerid)FROM
Fastelejer WHERE Pladsnummer = " + Pladsnummer;
The pladsnummer represents the input for their location. So the registration should put the user id into the location that is chosen.
In MS Access, "autoincrement" is usually called "identity". You can use the special ##IDENTITY variable to retrieve the ID of the last inserted identity column. Once you know the new ID, you can add it as a parameter in the second insert, like:
command.CommandText = "INSERT Table1 (...) values (...); SELECT ##IDENTITY";
var identity = (int) command.ExecuteScalar();
command.CommandText = "INSERT Table2 (user_id, ...) VALUES (#user_id, ...)";
command.Parameters.AddWithValue("#user_id", identity);
command.ExecuteNonQuery();
I have a web application that writes to several databases for tracking employee change requests. I am running into a problem with entering in a new employee. They are first written to main Employee database before their access information is written to the other databases with EMP_ID being the primary key. When it goes to write to the other databases EMP_ID has been generated yet so it is getting entered in as 0.
To resolve this I was trying to loop and check the EMP_ID value until a value is generated but I continue to get stuck in a loop because the query returns back that no value was found.
while (int.Parse(empIDChecker) == 0)
{
dbConnection.Open();
validateIDSQLString = "SELECT EMP_ID FROM EMPLOYEE_TABLE WHERE FIRST_NAME = '" + firstNameTextBox.Text.Trim() + "' AND LAST_NAME = '" + lastNameTextBox.Text.Trim() + "'";
SqlCommand updateSQLCmd = new SqlCommand(validateIDSQLString, dbConnection);
SqlDataReader getRecords = updateSQLCmd.ExecuteReader();
try
{
empIDChecker = getRecords["EMP_ID"].ToString();
}
catch
{
empIDChecker = "0";
}
getRecords.Close();
dbConnection.Close();
}
OK, so if your insert sproc looks something like:
sp_InsertEmp
...
INSERT INTO Emp(Name, etc...)
VALUES ('Paul', etc...)
SELECT SCOPE_IDENTITY() AS EMP_ID
GO
And in your code:
SqlCommand insertCmd = new SqlCommand("sp_InsertEmp", dbConnection);
... Add parameters here and set type to StoredProcedure
SqlDataReader dr= insertCmd.ExecuteReader();
int newId;
if (dr.Read())
{
newId = dr.GetInteger(0);
}
you can use
SELECT IDENT_CURRENT(‘tablename’)
This will give you the last inserted auto increment ID of the table, you can use that to insert in other table
Check this link as well http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
I found several examples of how to get the last inserted row id from an sql insert call to my SQLite database, but my script threw this error:
SQLiteException
Message = "SQLite error\r\nnear \")\": syntax error"
InnerException
NULL
Below is the SQL text I sent in and how I used it. Obviously, I misunderstood something. Could someone help me out here?
I am trying to return the ID number that was just inserted.
private static int Save(Dates date, SQLiteConnection con) {
// REF: http://www.sqlite.org/c3ref/last_insert_rowid.html
int result = 0;
string sql = "INSERT INTO Dates1 " +
"(ID, TaskID, Last1) " +
"VALUES " +
"((SELECT MAX(ID) FROM Dates1)+1, #TaskID, #Last); " +
"SELECT sqlite3_last_insert_rowid(sqlite3*);";
using (SQLiteCommand cmd = new SQLiteCommand(sql, con)) {
cmd.Parameters.AddWithValue(Dates.AT_TASK, date.TaskID);
cmd.Parameters.AddWithValue(Dates.AT_LAST, date.Last.ToShortDateString());
cmd.CommandText = Dates.SQL_INSERT;
try {
result = cmd.ExecuteNonQuery();
} catch (SQLiteException err) {
result = -1;
LogError("Save(Dates, SQLiteConnection)", err);
}
}
return result;
}
FYI: I have set up the table so that ID is supposed to be auto generated using the Create SQL below, but the table only stores -1 for the ID values unless I manually insert it.
public const string SQL_CREATE = "CREATE TABLE Dates1 " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT, TaskID INTEGER, Last1 TEXT);";
To quote from the SQLite documentation:
last_insert_rowid() The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.
So you need to change your statement to:
"SELECT last_insert_rowid();"
because what you did was to try and call the C API function.