Parameterized SQL statement: Difference between revisions

Added FreeBASIC
(Added FreeBASIC)
 
(11 intermediate revisions by 8 users not shown)
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}}==
 
<syntaxhighlight lang="rebol">; Helper functions
 
createTable: function [][
query db {!sql DROP TABLE IF EXISTS users}
query db {!sql
CREATE TABLE users (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT NOT NULL,
age INTEGER
)
}
]
 
addUser: function [name, email, age][
query.id db .with:@[name,email,age] {!sql
INSERT INTO users (username, email, age)
VALUES (?,?,?)
}
]
 
findUser: function [name][
query db .with:@[name] ~{!sql
SELECT *
FROM users
WHERE username=?
}
]
 
db: open.sqlite "users.db"
 
createTable
 
print ["added user with id:" addUser "JohnDoe" "jodoe@gmail.com" 35]
print ["added user with id:" addUser "JaneDoe" "jadoe@gmail.com" 14]
 
print ["getting user with name: JohnDoe =>" findUser "JohnDoe"]
 
close db</syntaxhighlight>
 
{{out}}
 
<pre>added user with id: 1
added user with id: 2
getting user with name: JohnDoe => [[1 JohnDoe jodoe@gmail.com 35]] </pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic"># open database file
dbopen "players.sqlite3"
 
# delete old players table - trap error if new database
onerror errortrap
# delete old database if it exists
dbexecute "DROP TABLE IF EXISTS players;"
 
# create database table with sample data
# include the IF NOT EXISTS clause to avoid an error if the table already exists.
dbexecute "CREATE TABLE IF NOT EXISTS players (name TEXT NOT NULL, score INTEGER, active BIT, jerseyNum INTEGER);"
dbexecute "INSERT INTO players VALUES ('Jones, Bob',0,'N',99)"
dbexecute "INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)"
dbexecute "INSERT INTO players VALUES ('Jello, Frank',0,'N',101)"
 
dbexecute "UPDATE players SET name = 'Smith, Steve', score = 42, active = 'TRUE' WHERE jerseyNum = 99;"
 
dbopenset "SELECT * FROM players;"
while dbrow()
print "['" + dbstring(0) + ", '" + dbstring(1) + ", '" + dbstring(2) + "', " + dbstring(3) + "]"
end while
dbcloseset
 
offerror
# wrap everything up
dbclose
end
 
errortrap:
# accept error - display nothing - return to next statement
return</syntaxhighlight>
{{out}}
<pre>Same as PureBasic entry.</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="vbnet">#include once "sqlite3.bi"
#define NULL 0
 
Dim As sqlite3 Ptr db
Dim As sqlite3_stmt Ptr stmt
Dim As Integer rc
 
' Open database file
rc = sqlite3_open("players.sqlite3", @db)
 
If rc <> SQLITE_OK Then
Print "No se puede abrir la base de datos: "; *sqlite3_errmsg(db)
sqlite3_close(db)
End 1
End If
 
' Delete old database if it exists
sqlite3_exec(db, "DROP TABLE IF EXISTS players;", NULL, NULL, NULL)
 
' Create database table with sample data
sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS players (name TEXT NOT NULL, score INTEGER, active BIT, jerseyNum INTEGER);", NULL, NULL, NULL)
sqlite3_exec(db, "INSERT INTO players VALUES ('Jones, Bob',0,'N',99)", NULL, NULL, NULL)
sqlite3_exec(db, "INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)", NULL, NULL, NULL)
sqlite3_exec(db, "INSERT INTO players VALUES ('Jello, Frank',0,'N',101)", NULL, NULL, NULL)
 
' Update name and score of player with jersey number 99
sqlite3_exec(db, "UPDATE players SET name = 'Smith, Steve', score = 42, active = 'TRUE' WHERE jerseyNum = 99;", NULL, NULL, NULL)
 
' Query and display all player table records
Dim As sqlite3_stmt Ptr stmt2
Dim As String query3 = "SELECT * FROM players"
rc = sqlite3_prepare_v2(db, Strptr(query3), -1, @stmt2, 0)
 
While sqlite3_step(stmt2) = SQLITE_ROW
Print "['"; *Cptr(ZString Ptr, sqlite3_column_text(stmt2, 0)); "', ";
Print *Cptr(ZString Ptr, sqlite3_column_text(stmt2, 1)); ", ";
Print *Cptr(ZString Ptr, sqlite3_column_text(stmt2, 2)); ", ";
Print sqlite3_column_int(stmt2, 3); "]"
Wend
 
' Close the database
sqlite3_finalize(stmt2)
sqlite3_close(db)
 
Sleep</syntaxhighlight>
{{out}}
<pre>Same as PureBasic entry.</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">UseSQLiteDatabase()
 
Procedure CheckDatabaseUpdate(database, query$)
result = DatabaseUpdate(database, query$)
If result = 0
PrintN(DatabaseError())
EndIf
ProcedureReturn result
EndProcedure
 
If OpenConsole()
If OpenDatabase(0, ":memory:", "", "")
;create players table with sample data
CheckDatabaseUpdate(0, "CREATE table players (name, score, active, jerseyNum)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jones, Bob',0,'N',99)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jello, Frank',0,'N',101)")
 
Define name$, score, active$, jerseynum
name$ = "Smith, Steve"
score = 42
active$ ="TRUE"
jerseynum = 99
SetDatabaseString(0, 0, name$)
SetDatabaseLong(0, 1, score)
SetDatabaseString(0, 2, active$)
SetDatabaseLong(0, 3, jerseynum)
CheckDatabaseUpdate(0, "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?")
;display database contents
If DatabaseQuery(0, "Select * from players")
While NextDatabaseRow(0)
name$ = GetDatabaseString(0, 0)
score = GetDatabaseLong(0, 1)
active$ = GetDatabaseString(0, 2)
jerseynum = GetDatabaseLong(0, 3)
row$ = "['" + name$ + "', " + score + ", '" + active$ + "', " + jerseynum + "]"
PrintN(row$)
Wend
FinishDatabaseQuery(0)
EndIf
CloseDatabase(0)
Else
PrintN("Can't open database !")
EndIf
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</syntaxhighlight>
 
Sample output:
<pre>['Smith, Steve', 42, 'TRUE', 99]
['Jesten, Jim', 0, 'N', 100]
['Jello, Frank', 0, 'N', 101]</pre>
 
==={{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.}}
<syntaxhighlight 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)")
#mem execute("INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)")
#mem execute("INSERT INTO players VALUES ('Jello, Frank',0,'N',101)")
sql$ = "
UPDATE players
SET name = 'Smith, Steve',
score = 42,
active = 'TRUE'
WHERE jerseyNum = 99"
#mem execute(sql$)
#mem execute("SELECT * FROM players ORDER BY jerseyNum")
WHILE #mem hasanswer()
#row = #mem #nextrow()
name$ = #row name$()
score = #row score()
active$ = #row active$()
jerseyNum = #row jerseyNum()
print name$;chr$(9);score;chr$(9);active$;chr$(9);jerseyNum
WEND
end</syntaxhighlight>
<pre>Output
Smith, Steve 42 TRUE 99
Jesten, Jim 0 N 100
Jello, Frank 0 N 101</pre>
 
=={{header|C}}==
Line 71 ⟶ 293:
 
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 184 ⟶ 406:
}
printf("\n");
}</langsyntaxhighlight>
 
{{out}}
Line 201 ⟶ 423:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System.Data.Sql;
using System.Data.SqlClient;
 
Line 210 ⟶ 432:
static void Main(string[] args)
{
SqlConnectionusing var tConn = new SqlConnection("ConnectionString");
 
SqlCommandusing var tCommand = new SqlCommandtConn.CreateCommand();
tCommand.Connection = tConn;
tCommand.CommandText = "UPDATE players SET name = @name, score = @score, active = @active WHERE jerseyNum = @jerseyNum";
 
Line 224 ⟶ 445:
}
}
}</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 261 ⟶ 482:
}
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 273 ⟶ 494:
 
; 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 293 ⟶ 514:
tCommand.ExecuteNonQuery() |> ignore
0</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 328 ⟶ 549:
}
rows.Close()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 339 ⟶ 560:
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 358 ⟶ 579:
 
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 403 ⟶ 624:
}
return ( 0 );
}</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
import java.sql.DriverManager;
import java.sql.Connection;
Line 442 ⟶ 663:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Line 448 ⟶ 669:
 
Uses the SQLite package.
<langsyntaxhighlight lang="julia">using SQLite
 
name = "Smith, Steve"
Line 466 ⟶ 687:
 
tbl = SQLite.query(db, "SELECT * from players")
println(tbl)</langsyntaxhighlight>
 
 
Line 477 ⟶ 698:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// Version 1.2.41
 
import java.sql.DriverManager
Line 500 ⟶ 721:
}
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 520 ⟶ 741:
}
Parametrized_Sql
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Needs["DatabaseLink`"];
{{incorrect|Mathematica|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.}}
conn=OpenSQLConnection[JDBC["ODBC(DSN)","testdb"],"Username"->"John","Password"->"JohnsPassword"];
<lang Mathematica>Needs["DatabaseLink`"];
SQLExecute[conn,"UPDATE players SET name = `1`, score = `2`, active = `3` WHERE jerseyNum = `4`", {SQLArgument["Smith, Steve",42,True,99]}]
conn=OpenSQLConnection[JDBC["ODBC(DSN)", "testdb"], "Username" -> "John", "Password" -> "JohnsPassword"];
CloseSQLConnection[conn];</syntaxhighlight>
SQLUpdate[conn,"players",{"name","score","active"},{"Smith, Steve", 42,"TRUE"},SQLColumn["jerseyNum"] = 99];
CloseSQLConnection[conn];</lang>
 
=={{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 670 ⟶ 890:
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 690 ⟶ 910:
echo row
 
db.close()</langsyntaxhighlight>
 
{{out}}
Line 696 ⟶ 916:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
use ODBC;
 
Line 714 ⟶ 934:
};
}
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 720 ⟶ 940:
{{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 843 ⟶ 1,063:
// Close the database connection.
sqlite3_close(db);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 859 ⟶ 1,079:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use DBI;
 
my $db = DBI->connect('DBI:mysql:mydatabase:host','login','password');
Line 865 ⟶ 1,085:
$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}}
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Parametrized_SQL_statement.exw
-- demo\rosetta\Parameterized_SQL_statement.exw
--
-- ============================================
include pSQLite.e
-- </span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (pSQLite)</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pSQLite</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #000080;font-style:italic;">--&lt;some pretty printing, not really part of the demo&gt;</span>
sqlite3 db = sqlite3_open(":memory:")
<span style="color: #008080;">constant</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">coltypes</span><span style="color: #0000FF;">,</span><span style="color: #000000;">colfmts</span><span style="color: #0000FF;">,</span><span style="color: #000000;">colrids</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({</span>
 
<span style="color: #0000FF;">{</span><span style="color: #000000;">SQLITE_INTEGER</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%4d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sqlite3_column_int</span><span style="color: #0000FF;">},</span>
integer res = sqlite3_exec(db,`create table players (name, score, active, jerseyNum)`)
<span style="color: #0000FF;">{</span><span style="color: #000000;">SQLITE_FLOAT</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%4g"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sqlite3_column_double</span><span style="color: #0000FF;">},</span>
res = sqlite3_exec(db,`insert into players values ('Roethlisberger, Ben', 94.1, 1, 7 )`)
<span style="color: #0000FF;">{</span><span style="color: #000000;">SQLITE_TEXT</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%-20s"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sqlite3_column_text</span><span style="color: #0000FF;">}})</span>
res = sqlite3_exec(db,`insert into players values ('Smith, Alex', 85.3, 1, 11)`)
res = sqlite3_exec(db,`insert into players values ('Doe, John', 15, 0, 99)`)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">what</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">sqlite3</span> <span style="color: #000000;">db</span><span style="color: #0000FF;">)</span>
res = sqlite3_exec(db,`insert into players values ('Manning, Payton', 96.5, 0, 123)`)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s:\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">what</span><span style="color: #0000FF;">})</span>
 
<span style="color: #000000;">sqlite3_stmt</span> <span style="color: #000000;">pStmt</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_prepare</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"SELECT * FROM players;"</span><span style="color: #0000FF;">)</span>
pp({"Before",sqlite3_get_table(db, "select * from players")},{pp_Nest,2})
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
 
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_step</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">)</span>
sqlite3_stmt pStmt = sqlite3_prepare(db, `update players set name=?, score=?, active=? where jerseyNum=?`)
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SQLITE_DONE</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
sqlite3_bind_text(pStmt,1,"Smith, Steve")
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SQLITE_ROW</span><span style="color: #0000FF;">)</span>
sqlite3_bind_double(pStmt,2,42)
<span style="color: #004080;">string</span> <span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
sqlite3_bind_int(pStmt,3,true)
<span style="color: #008080;">for</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">sqlite3_column_count</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
sqlite3_bind_int(pStmt,4,99)
<span style="color: #004080;">integer</span> <span style="color: #000000;">ctype</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_column_type</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">),</span>
res = sqlite3_step(pStmt);
<span style="color: #000000;">cdx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ctype</span><span style="color: #0000FF;">,</span><span style="color: #000000;">coltypes</span><span style="color: #0000FF;">),</span>
if res!=SQLITE_DONE then ?9/0 end if
<span style="color: #000000;">rid</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">colrids</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cdx</span><span style="color: #0000FF;">]</span>
if sqlite3_finalize(pStmt)!=SQLITE_OK then ?9/0 end if
<span style="color: #004080;">string</span> <span style="color: #000000;">name</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_column_name</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">),</span>
 
<span style="color: #000000;">data</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">colfmts</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cdx</span><span style="color: #0000FF;">],</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">))</span>
pp({"After",sqlite3_get_table(db, "select * from players")},{pp_Nest,2})
<span style="color: #000000;">text</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">" %s:%s"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data</span><span style="color: #0000FF;">})</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
sqlite3_close(db)</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">text</span><span style="color: #0000FF;">})</span>
<small>(The distributed version of this code displays nicer formatted output, but is nearly twice as long.)</small>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqlite3_finalize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SQLITE_OK</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000080;font-style:italic;">--&lt;/pretty printing&gt;</span>
<span style="color: #000000;">sqlite3</span> <span style="color: #000000;">db</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">":memory:"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqlite3_exec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`create table players (name, score, active, jerseyNum)`</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SQLITE_OK</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqlite3_exec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`insert into players values ('Roethlisberger, Ben', 94.1, 1, 7 )`</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SQLITE_OK</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqlite3_exec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`insert into players values ('Smith, Alex', 85.3, 1, 11)`</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SQLITE_OK</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqlite3_exec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`insert into players values ('Doe, John', 15, 0, 99)`</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SQLITE_OK</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqlite3_exec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`insert into players values ('Manning, Payton', 96.5, 0, 123)`</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SQLITE_OK</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Before"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">db</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--pp({"Before",sqlite3_get_table(db, "select * from players")},{pp_Nest,2})
-- For comparison against some other entries, this is how you would do numbered parameters:
--/*
sqlite3_stmt pStmt = sqlite3_prepare(db, `update players set name=?, score=?, active=? where jerseyNum=?`)
sqlite3_bind_text(pStmt,1,"Smith, Steve")
sqlite3_bind_double(pStmt,2,42)
sqlite3_bind_int(pStmt,3,true)
sqlite3_bind_int(pStmt,4,99)
--*/
-- However, ordinarily I would prefer named parameters and sqlbind_parameter_index() calls:</span>
<span style="color: #000000;">sqlite3_stmt</span> <span style="color: #000000;">pStmt</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_prepare</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">`update players set name=:name, score=:score, active=:active where jerseyNum=:jerseyn`</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">k_name</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_bind_parameter_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">":name"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">k_score</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_bind_parameter_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">":score"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">k_active</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_bind_parameter_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">":active"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">k_jerseyn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sqlite3_bind_parameter_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">":jerseyn"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sqlite3_bind_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k_name</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Smith, Steve"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sqlite3_bind_double</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k_score</span><span style="color: #0000FF;">,</span><span style="color: #000000;">42</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sqlite3_bind_int</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k_active</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sqlite3_bind_int</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k_jerseyn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">99</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqlite3_step</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SQLITE_DONE</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqlite3_finalize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pStmt</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SQLITE_OK</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"After"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">db</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--pp({"After",sqlite3_get_table(db, "select * from players")},{pp_Nest,2})</span>
<span style="color: #000000;">sqlite3_close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">db</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{"Before",:
{{" name":Roethlisberger, "Ben score",:94.1 "active",: 1 "jerseyNum"},: 7
name:Smith, Alex score:85.3 active: 1 jerseyNum: 11
{"Roethlisberger, Ben", "94.1", "1", "7"},
name:Doe, John score: 15 active: 0 jerseyNum: 99
{"Smith, Alex", "85.3", "1", "11"},
name:Manning, Payton score:96.5 active: 0 jerseyNum: 123
{"Doe, John", "15", "0", "99"},
After:
{"Manning, Payton", "96.5", "0", "123"}}}
name:Roethlisberger, Ben score:94.1 active: 1 jerseyNum: 7
{"After",
{{" name":Smith, "Alex score",:85.3 "active",: 1 "jerseyNum"},: 11
name:Smith, Steve score: 42 active: 1 jerseyNum: 99
{"Roethlisberger, Ben", "94.1", "1", "7"},
name:Manning, Payton score:96.5 active: 0 jerseyNum: 123
{"Smith, Alex", "85.3", "1", "11"},
{"Smith, Steve", "42.0", "1", "99"},
{"Manning, Payton", "96.5", "0", "123"}}}
</pre>
 
=={{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 929 ⟶ 1,193:
// 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}}==
<lang PureBasic>UseSQLiteDatabase()
 
Procedure CheckDatabaseUpdate(database, query$)
result = DatabaseUpdate(database, query$)
If result = 0
PrintN(DatabaseError())
EndIf
ProcedureReturn result
EndProcedure
 
 
If OpenConsole()
If OpenDatabase(0, ":memory:", "", "")
;create players table with sample data
CheckDatabaseUpdate(0, "CREATE table players (name, score, active, jerseyNum)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jones, Bob',0,'N',99)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jello, Frank',0,'N',101)")
 
Define name$, score, active$, jerseynum
name$ = "Smith, Steve"
score = 42
active$ ="TRUE"
jerseynum = 99
SetDatabaseString(0, 0, name$)
SetDatabaseLong(0, 1, score)
SetDatabaseString(0, 2, active$)
SetDatabaseLong(0, 3, jerseynum)
CheckDatabaseUpdate(0, "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?")
;display database contents
If DatabaseQuery(0, "Select * from players")
While NextDatabaseRow(0)
name$ = GetDatabaseString(0, 0)
score = GetDatabaseLong(0, 1)
active$ = GetDatabaseString(0, 2)
jerseynum = GetDatabaseLong(0, 3)
row$ = "['" + name$ + "', " + score + ", '" + active$ + "', " + jerseynum + "]"
PrintN(row$)
Wend
FinishDatabaseQuery(0)
EndIf
CloseDatabase(0)
Else
PrintN("Can't open database !")
EndIf
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</lang>
 
Sample output:
<pre>['Smith, Steve', 42, 'TRUE', 99]
['Jesten, Jim', 0, 'N', 100]
['Jello, Frank', 0, 'N', 101]</pre>
 
=={{header|Python}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="python">import sqlite3
 
db = sqlite3.connect(':memory:')
Line 1,024 ⟶ 1,228:
# 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,032 ⟶ 1,236:
{{works with|PostgreSQL}}
{{libheader|sql db-lib}}
<langsyntaxhighlight lang="racket">
#lang racket/base
(require sql db)
Line 1,055 ⟶ 1,259:
'("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,065 ⟶ 1,269:
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,102 ⟶ 1,306:
 
# and show the results
db.execute2('select * from players') {|row| p row}</langsyntaxhighlight>
outputs
<pre>["name", "score", "active", "jerseyNum"]
Line 1,108 ⟶ 1,312:
["John Doe", "-1", "false", "100"]
["Robert'; DROP TABLE players--", "3", "true", "101"]</pre>
 
=={{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.}}
<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)")
#mem execute("INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)")
#mem execute("INSERT INTO players VALUES ('Jello, Frank',0,'N',101)")
sql$ = "
UPDATE players
SET name = 'Smith, Steve',
score = 42,
active = 'TRUE'
WHERE jerseyNum = 99"
#mem execute(sql$)
#mem execute("SELECT * FROM players ORDER BY jerseyNum")
WHILE #mem hasanswer()
#row = #mem #nextrow()
name$ = #row name$()
score = #row score()
active$ = #row active$()
jerseyNum = #row jerseyNum()
print name$;chr$(9);score;chr$(9);active$;chr$(9);jerseyNum
WEND
end</lang>
<pre>Output
Smith, Steve 42 TRUE 99
Jesten, Jim 0 N 100
Jello, Frank 0 N 101</pre>
 
=={{header|Scala}}==
===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,198 ⟶ 1,372:
} yield n), Duration.Inf)
 
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 1,212 ⟶ 1,386:
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,243 ⟶ 1,417:
execute(testDb, "drop table players");
close(testDb);
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,252 ⟶ 1,426:
=={{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,291 ⟶ 1,465:
commit;
 
select * from players;</langsyntaxhighlight>
{{Out}}
<pre>SQL> SQL>
Line 1,312 ⟶ 1,486:
{{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,339 ⟶ 1,513:
 
SELECT * FROM PLAYERS @
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,378 ⟶ 1,552:
=={{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,399 ⟶ 1,573:
# 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.
<syntaxhighlight lang="wren">import "./sql" for Connection
 
var db = Connection.open("rc.db")
 
var createSql = [
"DROP TABLE IF EXISTS players",
"CREATE table players (name, score, active, jerseyNum)",
"INSERT INTO players VALUES ('Roethlisberger, Ben', 94.1, TRUE, 7)",
"INSERT INTO players VALUES ('Smith, Alex', 85.3, TRUE, 11)",
"INSERT INTO players VALUES ('Doe, John', 15, FALSE, 99)",
"INSERT INTO players VALUES ('Manning, Payton', 96.5, FALSE, 123)"
]
 
for (sql in createSql) db.exec(sql)
 
var widths = [22, 7, 7, 9]
System.print("Before update:\n")
db.printTable("SELECT * FROM players", widths)
 
var updateSql = "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = 99"
var ps = db.prepare(updateSql)
ps.bindText(1, "Smith, Steve")
ps.bindDouble(2, 42)
ps.bindBool(3, true)
ps.bindInt(4, 99)
ps.step()
 
System.print("\nAfter update:\n")
db.printTable("SELECT * FROM players", widths)</syntaxhighlight>
 
{{out}}
<pre>
Before update:
 
name score active jerseyNum
------------------------------------------------
Roethlisberger, Ben 94.1 1 7
Smith, Alex 85.3 1 11
Doe, John 15 0 99
Manning, Payton 96.5 0 123
 
After update:
 
name score active jerseyNum
------------------------------------------------
Roethlisberger, Ben 94.1 1 7
Smith, Alex 85.3 1 11
Smith, Steve 42.0 1 99
Manning, Payton 96.5 0 123
</pre>
 
{{omit from|360 Assembly}}
Line 1,415 ⟶ 1,643:
{{omit from|LC3 Assembly}}
{{omit from|Maxima}}
{{omit from|Minimal BASIC|No network access or built-in SQL}}
{{omit from|MIPS Assembly}}
{{omit from|OASYS Assembler}}
{{omit from|Palo Alto Tiny BASIC|No network access or built-in SQL}}
{{omit from|PARI/GP}}
{{omit from|PDP-11 Assembly}}
{{omit from|PDP-11 Assembly}}
{{omit from|Pentium Assembly}}
{{omit from|PL/0|No network access or built-in SQL}}
{{omit from|TI-83 BASIC|No network access or built-in SQL}}
{{omit from|TI-89 BASIC|No network access or built-in SQL}}
{{omit from|Tiny BASIC|No network access or built-in SQL}}
{{omit from|Unlambda|No network access or built-in SQL}}
{{omit from|VAX Assembly}}
2,122

edits