three dots menu of some sort windows sqlite3 - sql

When I try ls -1 (in powershell) to try and get into my table and check it, I get some sort of menu "...>" that I can't .quit out of. when I close out and run sqlite3 -init ex1.sql ex1.db (my example I'm working with, I get " Error: near line 1: table person already exists " when it in fact, does not. how do I get out of this menu, and how do I fix my code? Also, what IS this menu?
My sql code:
CREATE TABLE person (
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
age INTEGER
);

...> is shown by the sqlite3 command-line shell (not PowerShell) when you have not finished the current SQL command. Typically, you forgot the terminating ;, or you forgot a ' and are still inside a string.

Maybe you didn't specify what is the database in which you are working. For example before creating the table, use .open <name_database.db> and after run you CREATE TABLE statements.
Also the 3 dots ...> means that you didn't write the complete command, most often you didn't put the semicolon ; or you didn't close well the '. You can exit from this menu by killing the process or complete the command.

Related

How to create a SQL view when using multiple go statements? [duplicate]

How can I execute the following SQL inside a single command (single execution) through ADO.NET?
ALTER TABLE [MyTable]
ADD NewCol INT
GO
UPDATE [MyTable]
SET [NewCol] = 1
The batch separator GO is not supported, and without it the second statement fails.
Are there any solutions to this other than using multiple command executions?
The GO keyword is not T-SQL, but a SQL Server Management Studio artifact that allows you to separate the execution of a script file in multiple batches.I.e. when you run a T-SQL script file in SSMS, the statements are run in batches separated by the GO keyword. More details can be found here: https://msdn.microsoft.com/en-us/library/ms188037.aspx
If you read that, you'll see that sqlcmd and osql do also support GO.
SQL Server doesn't understand the GO keyword. So if you need an equivalent, you need to separate and run the batches individually on your own.
Remove the GO:
String sql = "ALTER TABLE [MyTable] ADD NewCol INT;";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "UPDATE [MyTable] SET [NewCol] = 1";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
It seems that you can use the Server class for that. Here is an article:
C#: Executing batch T-SQL Scripts containing GO statements
In SSMS (SQL Server Management System), you can run GO after any query, but there's a catch. You can't have the semicolon and the GO on the same line. Go figure.
This works:
SELECT 'This Works';
GO
This works too:
SELECT 'This Too'
;
GO
But this doesn't:
SELECT 'This Doesn''t Work'
;GO
This can also happen when your batch separator has been changed in your settings. In SSMS click on Tools --> Options and go to Query Execution/SQL Server/General to check that batch separator.
I've just had this fail with a script that didn't have CR LF line endings. Closing and reopening the script seems to prompt a fix. Just another thing to check for!
Came across this trying to determine why my query was not working in SSRS. You don't use GO in SSRS, instead use semicolons between your different statements.
I placed a semicolon ; after the GO, which was the cause of my error.
You will also get this error if you have used IF statements and closed them incorrectly.
Remember that you must use BEGIN/END if your IF statement is longer than one line.
This works:
IF ##ROWCOUNT = 0
PRINT 'Row count is zero.'
But if you have two lines, it should look like this:
IF ##ROWCOUNT = 0
BEGIN
PRINT 'Row count is zero.'
PRINT 'You should probably do something about that.'
END
I got this error message when I placed the 'GO' keyword after a sql query in the same line, like this:
insert into fruits (Name) values ('Apple'); GO
Writing this in two separate lines run. Maybe this will help someone...
I first tried to remove GO statements by pattern matching on (?:\s|\r?\n)+GO(?:\s|\r?\n)+ regex but found more issues with our SQL scripts that were not compatible for SQL Command executions.
However, thanks to #tim-schmelter answer, I ended up using Microsoft.SqlServer.SqlManagementObjects package.
string sqlText;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=FOO;Integrated Security=True;";
var sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
int result = server.ConnectionContext.ExecuteNonQuery(sqlText);

How to run SQLite3 'PRAGMA' commands via C-API?

Inside my C-program, I need to run the following pragma command:
const char *sql = "PRAGMA table_info(family)"; /* 'family' is the table name */
But whether i try to run this sql via sqlite3_exec() routine or sqlite3_prepare_v2() routine, my program stops responding/working at Windows command-prompt (it's a simple 'console program' in c-language).
Interestingly, when i run that same pragma sql at command-prompt normally by running the sqlite3.exe itself, it runs just fine and gives following output:
sqlite> pragma table_info(family);
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id INTEGER 0 1
1 name TEXT 1 0
2 nickname TEXT 1 0
3 dob TEXT 1 CURRENT_TI 0
But inside my own c-program it doesn't. I have done a bit research about this problem. Both Googling and SQLite Documentation point towards this page here at the official docs. But unfortunately the given information there hasn't enabled me enough to resolve the problem. How can we successfully run SQLite3 'PRAGMA' commands via C-API?
EDIT: Here are the actual problematic lines of code. OR MCVE
I have found the reasons of my program's failure, and have fixed it (Courtesy of clues and leads in Murphy's answer. But for those interested in reproducing the problem, here are the actual lines of code which were causing program to "crash".
Inside my callback function for sqlite3_exec() routine, I had this piece of code(for-loop) for printing ' ---------- ' characters below column names to mimic ".mode column" & ".headers on" style of output in sqlite3 console.
int h;
for(h=0; h <= (strlen(col_value[i])+5); h++)
printf("-");
The problem was being caused by strlen() while printing 'headers' for PRAGMA sql's result column dflt_value which is null for first three columns in my table. If i stop running strlen() on dflt_value. the program runs fine. Similarly, in sqlite3_prepare_v2() routine the problem was being caused by the following lines:
int h;
for(h=0; h <= (strlen(sqlite3_column_text(stmt, 4))+5); h++)
printf("-");
If i remove or comment these lines, all runs well - albeit without ".headers on" style.
sqlite3_exec() should indeed be the way to go to execute pragma commands. You didn't give a MCVE (shame on you!), but I suspect that you either neglect handling error values, or something else is wrong with your code. You should try debugging it.

PSQL lo_import in client side script

we have a simple sql script we maintain that sets up your schema and populates a set of text/example values - so it's just like create table, create table table insert into table... and we run it with a simple shell script which calls psql
one of our tables requires files - what I wanted to do was just have the files in the same directory as the script and do something like insert into repository (id, picture) values ('first', lo_import('first.jpg'))
but I get errors saying must be superuser to use server-side script. Is there any way I can achieve this? I have just a .sql file and a bunch of image files and by running psql against the file import them?
Running as superuser is not an option.
Using psql, you could write a shell script like
oid=`psql -At -c "\lo_import 'first.jpg'" | tail -1 | cut -d " " -f 2`
psql -Aqt -c "INSERT INTO repository (id, picture) values ('first', $oid)"
because comments can't have code - thanks to Laurenz, I got it "working" like this:
drop table if exists some_landing_table;
create table some_landing_table( load_time timestamp, filename varchar, data bytea);
\set the_file 'example.jpg';
\lo_import 'example.jpg';
insert into some_landing_table
select now(), 'example.jpg', string_agg(data,decode('','escape') order by pageno)
from
pg_largeobject
where
loid = (select max(loid) from pg_largeobject);
select lo_unlink( max(loid) ) from pg_largeobject;
however, that is ugly for two reasons -
I don't seem to be able to get the result of \lo_import into a variable in any way. even though select \lo_import filename works select \lo_import filename into x doesn't.
I can't use a variable - if I do \lo_import :the_file - it just says example.jpg doesn't exist - enven though if I put it in directly it works perfectly
I can't find a simpler way of providing a 0 length bytea field than decode('','escape')

Concatenating Substition variables with strings

I am modyfying a SQLplus script that creates a user, connects to the user and creates tables and puts values in those tables. This script had a set username and password for user like the below
CONNECT store/store_password#test
However I want to replace store_password with a variable v_store_password which I have put at the start:
ACCEPT v_store_password CHAR PROMPT 'Please type in store password: ' HIDE
Basically what I tried was this:
CONNECT store/&v_store_password || #test;
The above unfortunately does not work. I read some where that a "." can be used but it doesn't work.
How to concatenate or add to Substition variables?
Also how to add numbers to these variables?
/*make a file called file.connection.txt and enter username#password#tnsname#*//* write below code into batch file*/CLSECHO TITLE Database test script (ORACLE)#echo offclsfor /f "tokens=1-5 delims=#" %%a in (file_connection.txt) do (sqlplus -l "%%a/%%b#%%c " #test.sql)
exit
I actually dicovered that I have not included the & in front of variable like below
CREATE USER store IDENTIFIED BY v_store_password;
and the "." is varables concatenation character which ends them so the solution is:
CONNECT store/&v_store_password.#test;

Looping SQL query in Bash script

i am new to bash scripting and i was wondering if anyone could help me with the following.
I am trying to retrieve the competition name from a Oracle database using competition_id using the following statement:
select name, competition_type from competitions where competition_id=' ';
However i want to use a seperate text file whcih has a list competition_ids i want to identify, i want my script to find the name and type of all my ids and output the results in a txt file. this is what i have so far:
#!/bin/bash
echo Start Executing SQL commands
cat comps_ids.txt | while read ID
var=$ID
do
sqlplus "details"
<< EOF
select name, competition_type
from competitions
where competition_id=$var;
exit;
EOF
I tried to add a done at the end but i get "unexpected line ending" error message. Can anyone solve this?
Many thanks in advance :)
I'm not sure what your command line should look like, but it's more like
sqlplus "details" <<EOF
select name, competition_type from competitions where competition_id=$val;
exit;
EOF
If your list of IDs isn't too big, it may be better idea to make a ,-separated list and single query.
#!/bin/bash
function get_comp () {
sqlplus -S user/pass#database << EOF
set pagesize 0
set feedback off
set head off
select name, competition_type
from competitions
where competition_id=$1;
EOF
}
for id in $* ; do
get_comp $id
done
Put it in a file (get_comps.sh), and then call it like this
$ ./get_comps.sh < comp_ids.txt > text_file_out.txt
-S makes sqlplus quieter
The other setting make it return just your data, not row headers or anything else.
Of course the database credentials will be stored in your history, and available to other users using 'ps' or 'top'.
This is also horribly inefficient because it connects to the database for each row in your original file. If you have a lot of rows, you might try using python or ruby as their database stuff is pretty easy to use.