Jump to content

Parameterized SQL statement: Difference between revisions

m
syntax highlighting fixup automation
m (Use type inference. Wrap managed objects SqlConnection and SqlCommand in using statements to ensure they are closed on exiting method scope as per Microsoft docs https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection)
m (syntax highlighting fixup automation)
Line 2:
 
Using a SQL update statement like this one (spacing is optional):
<langsyntaxhighlight lang="sql">UPDATE players
SET name = 'Smith, Steve', score = 42, active = true
WHERE jerseyNum = 99</langsyntaxhighlight>show how to make a parameterized SQL statement, set the parameters to the values given above, and execute the statement.
 
<blockquote cite="http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/">Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.</blockquote>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">\ assuming the var 'db' contains an opened database with a schema matching the problem:
db @
"UPDATE players SET name=?1,score=?2,active=?3 WHERE jerseyNum=?4"
Line 21:
 
\ execute the query
db @ swap db:exec</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">-- Version for sqlite
with GNATCOLL.SQL_Impl; use GNATCOLL.SQL_Impl;
with GNATCOLL.SQL.Exec; use GNATCOLL.SQL.Exec;
Line 61:
Free (Conn);
Free (DB_Descr);
end Prepared_Query;</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">; Helper functions
 
createTable: function [][
Line 103:
print ["getting user with name: JohnDoe =>" findUser "JohnDoe"]
 
close db</langsyntaxhighlight>
 
{{out}}
Line 119:
 
Tested with gcc version 4.9.2 (Raspbian 4.9.2-10) and SQLite 3.8.7.1
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
Line 232:
}
printf("\n");
}</langsyntaxhighlight>
 
{{out}}
Line 249:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System.Data.Sql;
using System.Data.SqlClient;
 
Line 271:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{libheader|Qt}}
This example uses the Qt SQL module to access an ODBC data source.
<langsyntaxhighlight lang="cpp">#include <QtSql>
#include <iostream>
 
Line 308:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(require '[clojure.java.jdbc :as sql])
; Using h2database for this simple example.
(def db {:classname "org.h2.Driver"
Line 320:
 
; As an alternative to update!, use execute!
(sql/execute! db ["UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?" "Smith, Steve" 42 true 99])</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<langsyntaxhighlight lang="fsharp">open System.Data.SqlClient
[<EntryPoint>]
Line 340:
tCommand.ExecuteNonQuery() |> ignore
0</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 375:
}
rows.Close()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 386:
Example uses the [http://hackage.haskell.org/package/HDBC <tt>HDBC</tt>] package:
 
<langsyntaxhighlight lang="haskell">module Main (main) where
 
import Database.HDBC (IConnection, commit, run, toSql)
Line 405:
 
main :: IO ()
main = undefined</langsyntaxhighlight>
 
You'll need an instance of a type with an instance for the <tt>IConnection</tt> type class in order to use this function, such as [http://hackage.haskell.org/package/HDBC-postgresql-2.3.2.5/docs/Database-HDBC-PostgreSQL.html#t:Connection <tt>Connection</tt>] from [http://hackage.haskell.org/package/HDBC-postgresql <tt>HDBC-postgresql</tt>].
 
=={{header|Huginn}}==
<langsyntaxhighlight lang="huginn">import Database as db;
import Algorithms as algo;
import FileSystem as fs;
Line 450:
}
return ( 0 );
}</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
import java.sql.DriverManager;
import java.sql.Connection;
Line 489:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Line 495:
 
Uses the SQLite package.
<langsyntaxhighlight lang="julia">using SQLite
 
name = "Smith, Steve"
Line 513:
 
tbl = SQLite.query(db, "SELECT * from players")
println(tbl)</langsyntaxhighlight>
 
 
Line 524:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// Version 1.2.41
 
import java.sql.DriverManager
Line 547:
}
conn.close()
}</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Parametrized_Sql {
Base "rosetta" ' warning erase database if found it in current directory
Line 567:
}
Parametrized_Sql
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Needs["DatabaseLink`"];
conn=OpenSQLConnection[JDBC["ODBC(DSN)","testdb"],"Username"->"John","Password"->"JohnsPassword"];
SQLExecute[conn,"UPDATE players SET name = `1`, score = `2`, active = `3` WHERE jerseyNum = `4`", {SQLArgument["Smith, Steve",42,True,99]}]
CloseSQLConnection[conn];</langsyntaxhighlight>
 
=={{header|NetRexx}}==
Using an [http://db.apache.org/derby/ Apache Derby] embedded database:
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 716:
method isFalse() public static returns boolean
return \isTrue
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
Using an SQLite in memory database and "db_sqlite" high level binding from standard library.
<langsyntaxhighlight Nimlang="nim">import db_sqlite
 
let db = open(":memory:", "", "", "")
Line 736:
echo row
 
db.close()</langsyntaxhighlight>
 
{{out}}
Line 742:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
use ODBC;
 
Line 760:
};
}
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 766:
{{libheader|SQLite}}
Tested with Free Pascal 2.6.4 (arm) and SQLite 3.8.7.1
<langsyntaxhighlight lang="pascal">program Parametrized_SQL_Statement;
uses
sqlite3, sysutils;
Line 889:
// Close the database connection.
sqlite3_close(db);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 905:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use DBI;
 
my $db = DBI->connect('DBI:mysql:mydatabase:host','login','password');
Line 911:
$statment = $db->prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?");
 
$rows_affected = $statment->execute("Smith, Steve",42,'true',99);</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|SQLite}}
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Parameterized_SQL_statement.exw
Line 988:
<span style="color: #000000;">sqlite3_close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,004:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">$updatePlayers = "UPDATE `players` SET `name` = ?, `score` = ?, `active` = ?\n".
"WHERE `jerseyNum` = ?";
$dbh = new PDO( "mysql:dbname=db;host=localhost", "username", "password" );
Line 1,019:
// alternatively pass parameters as an array to the execute method
$updateStatement = $dbh->prepare( $updatePlayers );
$updateStatement->execute( array( "Smith, Steve", 42, 1, 99 ) );</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
As PicoLisp uses normal function calls for DB manipulations, parameters are always treated as plain data and are not executed.
<langsyntaxhighlight PicoLisplang="picolisp">(for P (collect 'jerseyNum '+Players 99)
(put!> P 'name "Smith, Steve")
(put!> P 'score 42)
(put!> P 'active T) )</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">UseSQLiteDatabase()
 
Procedure CheckDatabaseUpdate(database, query$)
Line 1,081:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
Sample output:
Line 1,090:
=={{header|Python}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="python">import sqlite3
 
db = sqlite3.connect(':memory:')
Line 1,114:
# and show the results
for row in db.execute('select * from players'):
print(row)</langsyntaxhighlight>
outputs
<pre>(u'Smith, Steve', 42, 1, 99)
Line 1,122:
{{works with|PostgreSQL}}
{{libheader|sql db-lib}}
<langsyntaxhighlight lang="racket">
#lang racket/base
(require sql db)
Line 1,145:
'("Smith, Steve" 42 #t 99))
 
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>use DBIish;
 
my $db = DBIish.connect('DBI:mysql:mydatabase:host','login','password');
Line 1,155:
my $update = $db.prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?");
 
my $rows-affected = $update.execute("Smith, Steve",42,'true',99);</langsyntaxhighlight>
 
=={{header|Ruby}}==
Using the {{libheader|sqlite3-ruby}} gem
[[Category:SQLite]]
<langsyntaxhighlight lang="ruby">require 'sqlite3'
 
db = SQLite3::Database.new(":memory:")
Line 1,192:
 
# and show the results
db.execute2('select * from players') {|row| p row}</langsyntaxhighlight>
outputs
<pre>["name", "score", "active", "jerseyNum"]
Line 1,201:
=={{header|Run BASIC}}==
{{incorrect|Run BASIC|Executing a NON-parameterized update DML. This solution is exactly the opposite of the task. This example is what is explicitly warned in the task.}}
<langsyntaxhighlight lang="runbasic">sqliteconnect #mem, ":memory:"
#mem execute("CREATE table players (name, score, active, jerseyNum)")
#mem execute("INSERT INTO players VALUES ('Jones, Bob',0,'N',99)")
Line 1,223:
print name$;chr$(9);score;chr$(9);active$;chr$(9);jerseyNum
WEND
end</langsyntaxhighlight>
<pre>Output
Smith, Steve 42 TRUE 99
Line 1,232:
===Using [http://slick.lightbend.com/doc/3.2.3/introduction.html Slick] FRM===
{{Out}}Best seen running in your browser [https://scastie.scala-lang.org/fJKRDaydSsGGlZQXJUhvxw Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">import slick.jdbc.H2Profile.api._
import slick.sql.SqlProfile.ColumnOption.SqlType
 
Line 1,288:
} yield n), Duration.Inf)
 
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 1,302:
A column from a result row is retrieved with the function [http://seed7.sourceforge.net/libraries/sql_base.htm#column%28in_sqlStatement,in_integer,attr_integer%29 column].
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "sql_base.s7i";
 
Line 1,333:
execute(testDb, "drop table players");
close(testDb);
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,342:
=={{header|SQL}}==
{{works with|Oracle}}
<langsyntaxhighlight lang="sql">-- This works in Oracle's SQL*Plus command line utility
 
VARIABLE P_NAME VARCHAR2(20);
Line 1,381:
commit;
 
select * from players;</langsyntaxhighlight>
{{Out}}
<pre>SQL> SQL>
Line 1,402:
{{works with|Db2 LUW}}
The following example is indeed parameterized SQL with named placeholders and it prevents SQL injections, and the SQL performs very well, because the execution plan is also precompiled.
<langsyntaxhighlight lang="sql pl">
--#SET TERMINATOR @
 
Line 1,429:
 
SELECT * FROM PLAYERS @
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,468:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# These next two lines are the only ones specific to SQLite
Line 1,489:
# With apologies to http://xkcd.com/327/
setPlayer $db 76 -> "Robert'; DROP TABLE players--" 0 false
$db close</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-sql}}
An embedded program using our SQLite wrapper.
<langsyntaxhighlight lang="ecmascript">import "./sql" for Connection
 
var db = Connection.open("rc.db")
Line 1,522:
 
System.print("\nAfter update:\n")
db.printTable("SELECT * FROM players", widths)</langsyntaxhighlight>
 
{{out}}
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.