Suppose I have two different arrays.
Emails = ["email#email.com", "email1#email.com", "email2#email.com"]
Names = ["Name Surname", "Name1, Surname1", "Name2, Surname2"]
And I have a mysql-table called Contacts, which I want to insert each of the values into rows called Emails and Names. Each name and email should be inserted at their according indexes. So Emails[0] should be inserted along with Names[0], Emails[1] with Names[1] etc.
If there was only one array. I could do something like
sql = "INSERT INTO Contacts (email)
VALUES
('#{email}')
Emails.each do |email|
email = email.sql
end
but now I have two arrays and I need to put them so that each email is associated according to the correct name. How do I do this?
Use zip:
con.prepare "INSERT INTO Contacts(email, name) VALUES(?, ?)"
Emails.zip(Names).each do |email,name|
#insert into db
con.execute(email,name) #assuming **con** is your connection object
end
You could do something like this if you really want to iterate:
Email.zip(Names).each do |email, name|
sql = "INSERT INTO Contacts (email, name) VALUES ('#{email}', '#{name)')"
end
alternatively, you can probably bulk insert using
sql = "INSERT INTO Contacts (email, name) VALUES (" +
Emails.zip(Names).map { |e, n| "('#{e}', '#{n}')" }.join(",") + ")"
Looks kind of ugly, but you get the idea
Related
I'm using the mysql-otp driver for Erlang. It seems to be working fine but there is no documentation on using it to insert multiple rows into a table.
simple use case for single row insert:
ok = mysql:query(Pid, "INSERT INTO mytable (id, bar) VALUES (?, ?)", [1, 42]).
But I need to insert multiple values, can I do something like this?
ok = mysql:query(Pid, "INSERT INTO mytable (id, bar) VALUES (?, ?)", [(1, 42),(2, 36), (3,12)]).
Documentation states Params = [term()], so probably not, which is a bummer.
You can certainly do a combination of lists:foldl/3 and lists:join/2 on your arguments to create the desired query format:
L = [[1, 42],[2, 36], [3,12]],
PreparedList = lists:foldl(fun (Params, Inserts) -> Inserts ++ [io_lib:format("(~p,~p)", Params)] end, [], L),
%% Then you need to join these with a comma:
Prepared = lists:flatten(lists:join(",", PreparedList)),
%% this will result in "(1,42),(2,36),(3,12)"
Now you just need to call the mysql insert with this Prepared variable:
ok = mysql:query(Pid, "INSERT INTO mytable (id, bar) VALUES ?", [Prepared]).
%% The query will look like: "INSERT INTO mytable (id, bar) VALUES (1,42),(2,36),(3,12)"
I don't think this driver or mysql can do such kind of things.
I think you should do it likes below
insert_mytable(Data)->
{ok,Ref} = mysql:prepare(Pid,insert_mytable,"INSERT INTO mytable (id, bar) VALUES (?, ?)"),
loop_insert(_Pid,Ref,Data).
loop_insert(_Pid,_Ref,[])-> ok;
loop_insert(Pid,Ref,[H|T])->
ok = mysql:execute(Pid,Ref,H),
loop_insert(Pid,Ref,T).
Presently I am inserting a new entry (copying the data from an existing entry) & then updating this new entry. eg:
$age = 30;
INSERT INTO table (category,sex,age) SELECT category,sex,age FROM table WHERE id = $id
<br>$new_id = mysql_insert_id();
<br>UPDATE sample_table SET age = $age WHERE id = $new_id
However, I would like to save a database interaction by inserting the new entry in one go (without having to get mysql_insert_id / updating the new entry). eg:
$age = 30;
INSERT INTO table (category,sex,$age) SELECT category,sex FROM table WHERE id = $id
Is there a way to insert the above by explicitly defining the age field, or is there another MYSQL command I should be using?
You are looking for this:
INSERT INTO table (category, sex, age)
SELECT category, sex, $age
FROM table
WHERE id = $id ;
You can put constants in the select list.
I am trying to insert records in 2 different mysql tables. Here's the situation:
Table 1: is_main that contains records of resorts with a primary key called id.
Table 2: is_features that contains a list of features that a resort can have (i.e. beach, ski, spa etc...). Each feature has got a primary key called id.
Table 3: is_i2f to connect each resort id with the feature id. This table has got 2 fields: id_i and id_f. Both fields are primary key.
I have created a form to insert a new resort, but I'm stuck here. I need a proper mysql query to insert a new resort in the is_main table and insert in is_i2f one record for each feature it has, with the id of the resort id id_i and the id of the feature id id_f.
$features = ['beach','relax','city_break','theme_park','ski','spa','views','fine_dining','golf'];
mysql_query("INSERT INTO is_main (inv_name, armchair, holiday, sipp, resort, price, rooms, inv_length, more_info)
VALUES ('$name', '$armchair', '$holiday', '$sipp', '$resort', '$price', '$rooms', '$length', '$more_info')");
$id = mysql_insert_id();
foreach($features as $feature) {
if(isset($_POST[$feature])) {
$$feature = 1;
mysql_query("INSERT INTO is_i2f (id_i, id_f) VALUES (" . $id . ", ?????????????? /missing part here????/ ); }
else {
$$feature = 0; }
}
Thanks.
Please, I'm going CrAzY!!!!!!!!!!!!!!
This may not be relevant to you, but...
Would it not make more sense to leave the link table unpopulated? You can use JOINs to then select what you need to populate the various views etc in your application
i.e. query to get 1 resort with all features:
SELECT
Id,
f.Id,
f.Name
FROM IS_MAIN m
CROSS JOIN IS_FEATURES f
WHERE m.Id = $RequiredResortId
Please find the answer on Mysql insert into 2 tables.
If you want to do multiple insert at a time you can write a SP to fulfill your needs
If I understand you correctly you could concatenate variable amount of to be inserted/selected values into one query. (This is the second query which needs an id from the first.)
//initializing variables
$id = mysql_insert_id();
$qTail = '';
$i = -1;
//standard beginning
$qHead = "INSERT INTO `is_i2f` (`id`,`feature`) VALUES ";
//loop through variable amount of variables
foreach($features] as $key => $feature) {
$i++;
//id stays the same, $feature varies
$qValues[$i] = "('{$id}', '{$feature}')";
//multiple values into one string
$qTail .= $qValues[$i] . ',';
} //end of foreach
//concatenate working query, need to remove last comma from $qTail
$q = $qHead . rtrim($qTail, ',');
Now you should have a usable insert query $q. Just echo it and see how it looks and test if it works.
Hope this was the case. If not, sorry...
I have a mysql database and a gridview. Now I want to count my inserts and updates. It has been suggested to set up a variables to represent each element e.g. nUpdates and nInserts, but I am unsure on how to do this? Here is the code I am using
For i = 0 To DataGridView1.RowCount - 1
Using dbSQL_cmd As New MySqlCommand()
student_id = DataGridView1.Item(i, 0).Value.ToString
name = DataGridView1.Item(i, 1).Value.ToString
age = DataGridView1.Item(i, 2).Value.ToString
adress = DataGridView1.Item(i, 3).Value.ToString.ToLower
dbSQL_query = "INSERT INTO student VALUES (?id, ?name, ?age, ?adress) " +
" on duplicate key update name=(name=?name, age=?age, adress=?adress)"
With dbSQL_cmd
.Parameters.AddWithValue("?id", student_id)
.Parameters.AddWithValue("?name", name)
.Parameters.AddWithValue("?age", age)
.Parameters.AddWithValue("?adress", adress)
' .Parameters.AddWithValue("?status", ?????)
.CommandText = dbSQL_query
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
dbSQL_cmd.ExecuteNonQuery()
End Using
Next
First, check the number of rows in the table before and after your insert/update loop. The difference between them is the number of rows you inserted.
You know how many items there are in your gridview. From your code, each one is either an insert or an update, so subtract the number of inserts you did (from that first step) from the number of items, and that is the number of rows you updated.
I'm trying to add a new mysql column in a table, using an insert_id from an insert of another table. This is the sentence that i use...
string sqlInsert = "INSERT INTO test (IdPico, Nombre, TextoBienvenida, FechaCreacion) VALUES (1, 'nombretest', 'aslkñdfa lsñdk asjd asldkf añlsj f', '2011-07-13 10:22:53'); ";
sqlInsert += "SET #IDTESTCREATED := CONCAT('Test', LAST_INSERT_ID(); ";
sqlInsert += "ALTER TABLE Usuarios ADD COLUMN #IDTESTCREATED BIT DEFAULT 0; ";
I using ASP.NET 4.0 and MySql connection, and server responds with 'Fatal error encountered during command execution. '
Could anybody help me?
Well ... I answer myself.
After making a deep search, I have not found how to add a column dynamically by a variable in mysql.
At end I had to make two querys, first to insert the test and get the id, and second to update the users table.
Since the insertion and retrieval of id are in the same query, no problems of persistent connections and concurrent updates.
string sqlInsert = "INSERT INTO Test (<fields>) VALUES (<values>);";
sqlInsert += "SELECT LAST_INSERT_ID() AS IdTestInserted; ";
string idnewtest = <result of insert query>;
string sqlAlter = "ALTER TABLE Users ADD COLUMN Test" + idnewtest + " BIT DEFAULT 0; ";
I regret not having found the answer, but at least I achieved my goal.
Thank you all for your help!