Inserting a variable into MySQL with Go - mysql

I have these 2 variables here
name := request.FormValue("username")
pass := request.FormValue("password")
I want to insert those 2 variables into my database
db.Query("INSERT INTO `godb` (`Username`, `Password`) VALUES ( )")
I tried (name,pass) ('name','pass') ($name, $pass) , none of them work.
Hope the question is not stupid, but I've been looking for solutions online but I did't understand them. Thanks !

From Using Prepared Statements
Parameter Placeholder Syntax
The syntax for placeholder parameters in prepared statements is
database-specific. For example, comparing MySQL, PostgreSQL, and
Oracle:
MySQL PostgreSQL Oracle
===== ========== ======
WHERE col = ? WHERE col = $1 WHERE col = :col
VALUES(?, ?, ?) VALUES($1, $2, $3) VALUES(:val1, :val2, :val3)
You tried PostgreSQL syntax but you use MySQL.

query should be in this format
db.Query("INSERT INTO table ($1, $2) VALUES (column1, column2)", value1, value2)
in your case something like that
db.Query("INSERT INTO godb ($1, $2) VALUES (username, password)", name, pass)

Related

MYSQL insert from select and variables

I am trying to insert values coming from a select and variable :
INSERT INTO routeur (`codeAdherent`, `quantiteArticle`, `dateFin`) VALUES
(SELECT `codeAdherent` FROM adherents WHERE categorie = 'G', `quantiteArticle` = $a, `dateFin`= $b);
Write it with and without VALUES, with and without IN, with and without brackets but I always get an synthax error.
Where is my mistake?
Try below:
INSERT INTO routeur (codeAdherent, quantiteArticle, dateFin)
SELECT codeAdherent, #a, #b FROM adherents WHERE categorie = 'G'
You have to read carefully the INSERT syntax because you have got many errors.
This is the right syntax:
INSERT INTO routeur (codeAdherent, quantiteArticle, dateFin)
SELECT codeAdherent, '$a', '$b'
FROM adherents
WHERE categorie = 'G'
PS: To avoid the SQL Injection you should use Prepared Statements
You can try this out :
INSERT INTO routeur (codeAdherent, quantiteArticle, dateFin) VALUES
(SELECT codeAdherent FROM adherents WHERE categorie = 'G', $a, $b);

Perl many insert statments into mysql database

I currently have code for perl that looks like this:
#valid = grep { defined($column_mapping{ $headers[$_] }) } 0 .. $#headers;
...
my $sql = sprintf 'INSERT INTO tablename ( %s ) VALUES ( %s )',
join( ',', map { $column_mapping{$_} } #headers[#valid] ),
join( ',', ('?') x scalar #valid);
my $sth = $dbh->prepare($sql);
...
my #row = split /,/, <INPUT>;
$sth->execute( #row[#valid] );
(Taken from mob's answer to a previous question.)
That is basically dynamically building a sql insert statement from csv data, and only allowing the csv data with proper headers from my column mapping to be picked.
I have been looking for examples on how to do an insert statment with multiple rows of data at once.
My perl script needs to run around a few hundred million insert statments, and doing it one at a time seems really slow, especially since the server I am running it on only has 6gb of ram and a slowish internet connection.
Is there a way I can upload more than 1 row at a time of data? So one insert statment uploads maybe 50 rows, or 100 rows at once? I cant find out how with perl DBI.
my $sql_values = join( ' ', ('(?, ?, ?)') x scalar(#array) );
As said before, then you can just flatten it.
You can insert multiple rows at once with the same syntax as in regular SQL, but you need to build your INSERT statemtent properly with Perl. Perl's slice() may help you:
Suppose you have 7 rows of data and want to insert them in chunks of 3 rows. "Regular" SQL would be like so:
insert into T (col1, col2) values ( 1, 2), ( 3, 4), ( 5, 6);
insert into T (col1, col2) values ( 7, 8), ( 9,10), (11,12);
insert into T (col1, col2) values (13,14);
Let's suppose your perl structure is like this:
my $values = [ [1,2], [3,4], ..., [13,14] ];
If it's not, bring it into this shape. Now:
use constant CHUNKSIZE => 3;
my $stmt = sprintf( 'insert into T (col1, col2) values %s',
join(',', '(?,?)' x CHUNKSIZE) );
# $stmt is now 'insert into T (col1, col2) values (?,?),(?,?),(?,?)'
my $sth = $dbh->prepare($stmt);
while( my #chunk = splice( #{$values}, 0, CHUNKSIZE ) ) {
# #chunk has 3 elements (rows), or less for the last chunk
if (scalar #chunk == CHUNKSIZE) {
$sth->execute( #chunk ); # inserts 3 rows at once
} else {
# build and prepare a new statement for the remaining rows.
# in our sample there is only 1 remaining row.
$stmt = sprintf( 'insert into T (col1, col2) values %s',
join(',', '(?,?)' x scalar #chunk) );
$sth = $dbh->prepare($stmt);
$sth->execute( #chunk ); # inserts the last row
}
}

How to use $RANDOM (linux) in a mySQL command-line query?

I am trying to insert random values into a table from my linux terminal, but when i use the following SQL statement,
INSERT INTO kCreate (k1 , k2) VALUES ('$RANDOM' , '$RANDOM');
where k1 and k2 are of datatype INT, 0 is being inserted instead of a random value, What am i doing wrong here ?
k1 and k2 are of INT type, no need to put the value inside single quote, try this:
sql="INSERT into kcreate ( k1, k2) values ($RANDOM, $RANDOM);"
echo $sql | mysql -ppassword test
You can use rand() function of mysql with ceil(). Here is an example.
INSERT INTO kCreate (k1 , k2)
VALUES (ceil(rand()*1000) , ceil(rand()*1000));

Inserting data into the mysql database from perl

I am trying to insert data into a MySQL database:
$response = $client->fql->query(
query => '
SELECT name, email, birthday, username, first_name, last_name, pic
FROM user
WHERE uid = me()
',
);
print join "\n Name:", sort map { $_->{name} } #$response;
$dbh->do("
INSERT INTO Users(SNo,Name,Email,Birthday,UserName,FirstName,LastName)
VALUES(1,
sort map { $_->{name} } #$response,
'imm\#gmail.com',
'1987/12/10',
'imm',
'imm',
'Dee')
");
$dbh->disconnect();
used the mysql query in one line.
This above print statement is printing the name correctly but why the above sql insert statement is not working?
I connect the db and after that i am receiving the value and printing in the browser is working.
Why does the mysql statement not accept the value?
When inserting the database is not working?
You should have a look at the official doc
and specially this :
# INSERT some data into 'foo'. We are using $dbh->quote() for
# quoting the name.
$dbh->do("INSERT INTO foo VALUES (1, " . $dbh->quote("Tim") . ")");
# Same thing, but using placeholders
$dbh->do("INSERT INTO foo VALUES (?, ?)", undef, 2, "Jochen");

INSERT INTO with subquery & parameters not working in MS-Access

I have an INSERT INTO which works fine with the parameters as constants:
INSERT INTO FinalValidityCodes
(tblReceivedSamplersID, Substudy, Location, FinalValidityCode, DateTimeProcessed)
SELECT ID, true, 'I', 0, now()
FROM tblReceivedSamplers
WHERE (SampleID = ?)
This would affect 1 row (as expected)
Yet if I change the query to use parameters it will allow it to run but will never affect any rows.
INSERT INTO FinalValidityCodes
(tblReceivedSamplersID, Substudy, Location, FinalValidityCode, DateTimeProcessed)
SELECT ID, ?, ?, ?, ?
FROM tblReceivedSamplers
WHERE (SampleID = ?)
What is the difference and why, when I use parameters, does the Insert, seemingly, fail?
Edit:
SampleID is a text datatype.
It looks like the purpose of that INSERT is to add a single row to FinalValidityCodes with values for 5 fields. However, 4 of those values will be supplied directly by query parameters, and ID/tblReceivedSamplersID will be derived from another parameter.
So I would try a DLookup() expression to get the ID (using the parameter for SampleID), and insert that value along with the other 4 parameter values. Here is an untested guess.
INSERT INTO FinalValidityCodes (
tblReceivedSamplersID,
Substudy,
Location,
FinalValidityCode,
DateTimeProcessed
)
VALUES (
DLookup("ID", "tblReceivedSamplers", "SampleID ='" & param1 & "'"),
param2,
param3,
param4,
param5
);