How can I insert parameter with value from database.
I have some field and I should insert value from this database + 1 (with plus one)
For example
myCommand.CommandText =
"INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES (#game_nr, #game_player_id, #game_nrontable, #game_role_id)"
'Example
myCommand.Parameters.Add("#game_nr", SqlDbType.Int).Value = **"(SELECT MAX(GAME_NR) FROM GAMES)" + 1**
You don't. You make GAME_NR and auto-incremented primary key:
create table games (
game_nr int auto_increment primary key,
. . .
);
Then you do the insert as:
INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID)
VALUES (#game_player_id, #game_nrontable, #game_role_id);
Let the database do the work.
You don't need the parameter, you can try following code.
myCommand.CommandText =
"INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES ((SELECT MAX(GAME_NR) + 1 FROM GAMES), #game_player_id, #game_nrontable, #game_role_id)"
But it looks like a primary key of the table. If Game_Nr is pr, You should use auto-inc. identity, then you don't need this param.
It will be.
myCommand.CommandText =
"INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES (#game_player_id, #game_nrontable, #game_role_id)"
Related
I have 2 tables being:
'bin' and 'missedbin' ,missed bin contains a foreign key or the primay key 'binID' from bin. I have set the foreign key to cascade on update & delete.
However, when a value is inserted into bin the foreign key is not updated within the missedbin table and remains null. Have I done something incorrectly?
EDIT:
missedbin table:
bin table:
I have 2 insert statements running in asp:
cmd.CommandText = "insert into mydb1.bin values(null,'" + binType + "','" + binColour + "','" + personIDdata + "')";
cmd.CommandText = "insert into mydb1.missedbin values (null, '" + personIDdata + "','" + dateFound + "', null)";
The foreign key does not work that way. You have to provide the correct binID when inserting into missedBin (always). You can use LAST_INSERT_ID(). Only if you later change bin.binID, then the binID in missedBin will change as well
INSERT INTO bin () VALUES () ...
INSERT INTO missedbin (binID, ...) VALUES (LAST_INSERT_ID(), ...)
I am trying to use the query below to insert a concatenated converted set of integers to string for use on a datetime field in my table.
TABLE
Field Type
empID int(11)
time_stamp datetime
in_out char(3)
am_pm char(2)
QUERY
Dim query As String = "INSERT INTO attendance VALUES(" & empID.Text & _
"STR_TO_DATE(CONCAT("& empYear.Text & ",'-'," & empMonth.Text & ",'-'," & _
empDay.Text & ",' '," & empHour.Text & ",':'," & empMin.Text & ",':'," & _
empSec.Text & ",'%Y-%m-%d %H:%i:%s'),'out','pm')"
There is no problem with the connection and the values. I have tried to insert the values into a test column of string type and the output is this:
133201712311827
I am pretty sure it's with how I use these characters: '' "" "," - :. I just can't figure out how.
First problem I see, here
& empID.Text & "STR_TO_DATE(. . . .
you're missing comma after first value
& empID.Text & "***,*** STR_TO_DATE(. . . .
Second issue, I identified when I've replaced your text values with hard coded values - You are missing closing parenthesis for str_to_date. Here ,'%Y-%m-%d... should be ), '%Y-%m-%d...
STR_TO_DATE(CONCAT(1999,'-',01,'-',01,' ',10,':',25,':',30***)***,'%Y-%m-%d %H:%i:%s')
As you see- my replacement shows that you have no issues with concatenation, single quote and :. Theo only other variable here is quality of data in text boxes.
Update
This answer (above) is correct. Using sql fiddle I created schema and when replaced text box values with hard-coded ones - all worked. My suggestions to add comma and parenthesis hold true. Your claim about problems with single quotes are false.
create table xxx (empID int(11), time_stamp datetime, in_out char(3), am_pm char(2));
INSERT INTO xxx VALUES(123,
STR_TO_DATE(CONCAT('2017','-','1','-','23',' ','10',':','35',':','40'),'%Y-%m-%d %H:%i:%s'),
'out','pm');
commit;
Select * from xxx
empID | time_stamp | in_out | am_pm
123 | January, 23 2017 10:35:40 | out | pm
End Update
On top of that, you could do it much better by parameterizing, which will look like something like this
command.CommandText = "insert into ... values (#1, #2, #3, #4)"
command.Parameters.AddWithValue("#1", Convert.ToInt32(empID.Text))
dim date as new DateTime(Convert.ToInt32(empYear.Text), Convert.ToInt32(empMonth.Text), . . . . )
command.Parameters.AddWithValue("#2", date)
. . . . . .
command.ExecuteNonQuery()
Parameterizing will make it easy to work with dates and strings
this is where I am getting my info from, and when I choose the address it fills in all the info
but the problem starts when I try to add a renter to the renter table after I have deleted a renter. this table no longer shows columns with all addressIDs so I am trying to insert the AddressID as well from the property table.I hope this makes sense
I cant insert pictures yet, but here is what it looks like when i chose a property, rentals
if ( ( evt.getStateChange() == java.awt.event.ItemEvent.SELECTED ) &&
( PropertyComboBox.getSelectedIndex() != 0 ) )
{
Address = ( String ) PropertyComboBox.getSelectedItem();
try {
myResultSet = myStatement.executeQuery(
"SELECT Property.Address,Property.AddressID,Property.RentAmt, Renter.RenterID, Renter.AddressID, Renter.FirstName, Renter.LastName, Renter.CellPhone, Renter.DepositPaid,Renter.DepositAmtPaid " +
"FROM Property, Renter " +
"WHERE Property.Address = '" + Address + "'" + "AND Renter.AddressID = Property.AddressID" );
if (myResultSet.next())
{
renterID = (myResultSet.getString("Renter.RenterID"));
addressID = (myResultSet.getString("Property.AddressID"));
txtRentAmt.setText(myResultSet.getString("Property.RentAmt"));
txtShowAddressID.setText(myResultSet.getString("Property.AddressID"));
txtShowRenterID.setText(myResultSet.getString("Renter.RenterID"));
txtFirstName.setText(myResultSet.getString("Renter.FirstName"));
txtLastName.setText(myResultSet.getString("Renter.LastName"));
txtCellPhone.setText(myResultSet.getString("Renter.CellPhone"));
txtDepositPaid.setText(myResultSet.getString("Renter.DepositPaid"));
txtDepositAmtPaid.setText(myResultSet.getString("Renter.DepositAmtPaid"));
if(myResultSet.getString("Renter.DepositPaid") == ("Y"))
{
txtDepositPaid.setText("Y");
}
else
{
txtDepositPaid.setText("N");
}
}
}
can someone help me with this ? I am trying to insert a new renter
from a netbeans jform into my database. The AddressID
(PK,auto-increment ) from the property table should automatically
insert into the renter table AddressID (FK, auto-increment(so I
thought)
It will insert if I use this statement but then the addressID shows as
NULL, not the AddressID from the property table, which I need. Ive
been working on this since Saturday. UGH Please help! very simple, yet
I cannot figure it out
ls_query = "INSERT INTO Renter (FirstName,LastName,CellPhone,DepositPaid,DepositAmtPaid)"
+ " VALUES (" + addressID + ",'"
+ addFirstName + "','"
+ addLastName + "','"
+ addCellPhone + "','"
+ addDepositPaid + "',"
+ addDepositAmtPaid + ")" + " WHERE Property.AddressID = " + addressID ;
INSERT plus WHERE? i guess you need UPDATE, not INSERT http://dev.mysql.com/doc/refman/5.0/en/update.html
EDIT: it's not clear, you are mixing in insert in one table with a where in another table?, just do "INSERT ... (fields) VALUES (values)" without WHERE and specify all addressID on fields.
You need to specify AddressID in the field list.
...INTO Renter (AddressID, FirstName...
Assuming that you specify all columns in the table, you can omit the field list.
You may also be more comfortable with the INSERT ... SET syntax.
I have a insert statement in MS Access which needs to be wrapped in single quotes so that it can be passed as string to a column in another table. here is my insert statement below
Insert into Employee(EmpName,EmpDepartment) Values ('Mike',NULL)
when I wrap I am getting errors arounf 'Mike'
'Insert into Employee(EmpName,EmpDepartment) Values ('Mike',NULL)'
Below is my create table with two primary keys
create table Employee([OBJECTID] AUTOINCREMENT(1, 1), EmpName Text(10), EmpDepartment Text(50), Primary Key (OBJECTID, EmpName))
How can I set default values to EmpName as Mike and Null to EmpDepartment while creating table it self ??
You will need ADO to create a default easily with a standard SQL mode for Access. This will run in VBA.
sSQL = "create table Employee([OBJECTID] AUTOINCREMENT(1, 1), " _
& "EmpName Text(10) default mike, EmpDepartment Text(50), " _
& "Primary Key (OBJECTID, EmpName))"
CurrentProject.Connection.Execute sSQL
I am trying to insert the guestpass type name in table guestpasstypes and at a time it will check the database whether the database has already that name or not by using this statement:
#"INSERT INTO guestpasstypes(guestPasstype_Name)values('" + tbPassType.Text + "') where not exists (select 'guestPasstype_Name' from guestpasstypes where guestPasstype_Name = '" + tbPassType.Text + "')"
but it accepts the duplicate name too, and it does not work. Would anyone please help on this?
For SQL Server it would look like this.
insert into guestpasstypes (guestPasstype_Name)
select 'name1'
where not exists (select *
from guestpasstypes
where guestPasstype_Name = 'name1')
I think it should work for MySQL as well.
If you are on SQL Server 2008 you can use MERGE.
merge guestpasstypes as G
using (select 'name2') as S(Name)
on G.guestPasstype_Name = S.Name
when not matched then
insert (guestPasstype_Name) values (Name);
UPDATE
I think the first option could be applied to your problem like this:
#"INSERT INTO guestpasstypes(guestPasstype_Name) select '" + tbPassType.Text
+ "' where not exists (select * from guestpasstypes where guestPasstype_Name = '"
+ tbPassType.Text + "')"
If you want it to throw an error you can either :
Put a unique index on the column (the easiest and preferred way)
or
Write a stored procedure which returns an error flag. Within the procedure, you first check for a matching value and if one is found, set the error flag and return. Otherwise do the insert as normal.
Try either INSERT IGNORE or INSERT ON DUPLICATE KEY:
INSERT IGNORE INTO `guestpasstypes`(`guestPasstype_Name`) values('" + tbPassType.Text + "');
OR
INSERT INTO `guestpasstypes`(`guestPasstype_Name`)values('" + tbPassType.Text + "') ON DUPLICATE KEY UPDATE `guestPasstype_Name` = `guestPasstype_Name`;