How to use user input to create databases - database

How do I get input from user to create databases in python? These data must stored in test.db file.
Code
import sqlite3
conn = sqlite3.connect('test.db');
print "Opened database successfully";
name=raw_input ("enter your name: ");
salary=raw_input("enter your salary: ");
conn.execute("INSERT INTO employee (NAME,SALARY) \
VALUES ( r"+name+",r "+salary+")");
conn.commit()

Your concatenation is broken here, if salary is an integer you should do something like that:
conn.execute("INSERT INTO employee (NAME,SALARY) \
VALUES ( \"" + name + "\", " + str(salary) + ")");
Basically you need to escape some quotes around strings in your query.
Then to read your table you can do something like that:
for row in conn.execute('SELECT * FROM employee'):
print row

Related

I am struggling to select a string of data from a database table and print it as a variable

I've been trying to learn how to use sqlite3 for python 3.10 and I can't find any explanation of how I'm supposed to grab saved data From a database and insert it into a variable.
I'm attempting to do that myself in this code but It just prints out
<sqlite3.Cursor object at 0x0000018E3C017AC0>
Anyone know the solution to this?
My code is below
import sqlite3
con = sqlite3.connect('main.db')
cur = con.cursor()
#Create a table called "Datatable" if it does not exist
cur.execute('''CREATE TABLE IF NOT EXISTS datatable
(Name PRIMARY KEY, age, pronouns) ''')
# The key "PRIMARY KEY" after Name disallow's information to be inserted
# Into the table twice in a row.
name = 'TestName'#input("What is your name? : ")
age = 'TestAge'#input("What is your age? : ")
def data_entry():
cur.execute("INSERT INTO datatable (name, age)")
con.commit
name = cur.execute('select name from datatable')
print(name)
Expected result from Print(name) : TestName
Actual result : <sqlite3.Cursor object at 0x00000256A58B7AC0>
The execute statement fills the cur object with data, but then you need to get the data out:
rows = cur.fetchall()
for row in rows:
print(row)
You can read more here: https://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/

Oracle Select query doesnt return any results when using trim on char(2) column and database field has only spaces

Oracle Select query is not returning any results when using trim on char(2) column. The database field has only spaces. However, when the field has a space and a character, I get the correct results.
e.g.
Action_code char(2)
val = " 8"
Select * from abc where trim(Action_code) = trim(val)
Here I get the rows having " 8".
But,
val = " "
Select * from abc where trim(Action_code) = trim(val)
Here I don't get any rows from database where Action_code is " ". But I have such rows in database.
Can someone please help me how to get rows in 2nd case?
I just found that when you trim a variable or database column which has only spaces, it is treated as null by Oracle. So the following query works:
val = " "
Select * from abc where trim(Action_code) is null and trim(val) is null
Now I get the rows from database where Action_code is " ".
Why you don't try to use the nvl function ?
nvl(valueIsNull,returnOtherValue)
?

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

I inherited a project and I'm running into a SQL error that I'm not sure how to fix.
On an eCommerce site, the code is inserting order shipping info into another database table.
Here's the code that is inserting the info into the table:
string sql = "INSERT INTO AC_Shipping_Addresses
(pk_OrderID, FullName, Company, Address1, Address2, City, Province, PostalCode, CountryCode, Phone, Email, ShipMethod, Charge_Freight, Charge_Subtotal)
VALUES (" + _Order.OrderNumber;
sql += ", '" + _Order.Shipments[0].ShipToFullName.Replace("'", "''") + "'";
if (_Order.Shipments[0].ShipToCompany == "")
{
sql += ", '" + _Order.Shipments[0].ShipToFullName.Replace("'", "''") + "'";
}
else
{
sql += ", '" + _Order.Shipments[0].ShipToCompany.Replace("'", "''") + "'";
}
sql += ", '" + _Order.Shipments[0].Address.Address1.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Address2.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.City.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Province.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.PostalCode.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Country.Name.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Phone.Replace("'", "''") + "'";
if (_Order.Shipments[0].ShipToEmail == "")
{
sql += ",'" + _Order.BillToEmail.Replace("'", "''") + "'";
}
else
{
sql += ",'" + _Order.Shipments[0].ShipToEmail.Replace("'", "''") + "'";
}
sql += ", '" + _Order.Shipments[0].ShipMethod.Name.Replace("'", "''") + "'";
sql += ", " + shippingAmount;
sql += ", " + _Order.ProductSubtotal.ToString() + ")";
bll.dbUpdate(sql);
It is working correctly, but it is also outputting the following SQL error:
Violation of PRIMARY KEY constraint 'PK_AC_Shipping_Addresses'. Cannot insert
duplicate key in object 'dbo.AC_Shipping_Addresses'. The duplicate key value
is (165863).
From reading similar questions, it seems that I should declare the ID in the statement.
Is that correct? How would I adjust the code to fix this issue?
I was getting the same error on a restored database when I tried to insert a new record using the EntityFramework. It turned out that the Indentity/Seed was screwing things up.
Using a reseed command fixed it.
DBCC CHECKIDENT ('[Prices]', RESEED, 4747030);GO
I'm pretty sure pk_OrderID is the PK of AC_Shipping_Addresses
And you are trying to insert a duplicate via the _Order.OrderNumber?
Do a
select * from AC_Shipping_Addresses where pk_OrderID = 165863;
or select count(*) ....
Pretty sure you will get a row returned.
It is telling you that you are already using pk_OrderID = 165863 and cannot have another row with that value.
if you want to not insert if there is a row
insert into table (pk, value)
select 11 as pk, 'val' as value
where not exists (select 1 from table where pk = 11)
What is the value you're passing to the primary key (presumably "pk_OrderID")? You can set it up to auto increment, and then there should never be a problem with duplicating the value - the DB will take care of that. If you need to specify a value yourself, you'll need to write code to determine what the max value for that field is, and then increment that.
If you have a column named "ID" or such that is not shown in the query, that's fine as long as it is set up to autoincrement - but it's probably not, or you shouldn't get that err msg. Also, you would be better off writing an easier-on-the-eye query and using params. As the lad of nine years hence inferred, you're leaving your database open to SQL injection attacks if you simply plop in user-entered values. For example, you could have a method like this:
internal static int GetItemIDForUnitAndItemCode(string qry, string unit, string itemCode)
{
int itemId;
using (SqlConnection sqlConn = new SqlConnection(ReportRunnerConstsAndUtils.CPSConnStr))
{
using (SqlCommand cmd = new SqlCommand(qry, sqlConn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Unit", SqlDbType.VarChar, 25).Value = unit;
cmd.Parameters.Add("#ItemCode", SqlDbType.VarChar, 25).Value = itemCode;
sqlConn.Open();
itemId = Convert.ToInt32(cmd.ExecuteScalar());
}
}
return itemId;
}
...that is called like so:
int itemId = SQLDBHelper.GetItemIDForUnitAndItemCode(GetItemIDForUnitAndItemCodeQuery, _unit, itemCode);
You don't have to, but I store the query separately:
public static readonly String GetItemIDForUnitAndItemCodeQuery = "SELECT PoisonToe FROM Platypi WHERE Unit = #Unit AND ItemCode = #ItemCode";
You can verify that you're not about to insert an already-existing value by (pseudocode):
bool alreadyExists = IDAlreadyExists(query, value) > 0;
The query is something like "SELECT COUNT FROM TABLE WHERE BLA = #CANDIDATEIDVAL" and the value is the ID you're potentially about to insert:
if (alreadyExists) // keep inc'ing and checking until false, then use that id value
Justin wants to know if this will work:
string exists = "SELECT 1 from AC_Shipping_Addresses where pk_OrderID = " _Order.OrderNumber; if (exists > 0)...
What seems would work to me is:
string existsQuery = string.format("SELECT 1 from AC_Shipping_Addresses where pk_OrderID = {0}", _Order.OrderNumber);
// Or, better yet:
string existsQuery = "SELECT COUNT(*) from AC_Shipping_Addresses where pk_OrderID = #OrderNumber";
// Now run that query after applying a value to the OrderNumber query param (use code similar to that above); then, if the result is > 0, there is such a record.
To prevent inserting a record that exist already. I'd check if the ID value exists in the database. For the example of a Table created with an IDENTITY PRIMARY KEY:
CREATE TABLE [dbo].[Persons] (
ID INT IDENTITY(1,1) PRIMARY KEY,
LastName VARCHAR(40) NOT NULL,
FirstName VARCHAR(40)
);
When JANE DOE and JOE BROWN already exist in the database.
SET IDENTITY_INSERT [dbo].[Persons] OFF;
INSERT INTO [dbo].[Persons] (FirstName,LastName)
VALUES ('JANE','DOE');
INSERT INTO Persons (FirstName,LastName)
VALUES ('JOE','BROWN');
DATABASE OUTPUT of TABLE [dbo].[Persons] will be:
ID LastName FirstName
1 DOE Jane
2 BROWN JOE
I'd check if i should update an existing record or insert a new one. As the following JAVA example:
int NewID = 1;
boolean IdAlreadyExist = false;
// Using SQL database connection
// STEP 1: Set property
System.setProperty("java.net.preferIPv4Stack", "true");
// STEP 2: Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// STEP 3: Open a connection
try (Connection conn1 = DriverManager.getConnection(DB_URL, USER,pwd) {
conn1.setAutoCommit(true);
String Select = "select * from Persons where ID = " + ID;
Statement st1 = conn1.createStatement();
ResultSet rs1 = st1.executeQuery(Select);
// iterate through the java resultset
while (rs1.next()) {
int ID = rs1.getInt("ID");
if (NewID==ID) {
IdAlreadyExist = true;
}
}
conn1.close();
} catch (SQLException e1) {
System.out.println(e1);
}
if (IdAlreadyExist==false) {
//Insert new record code here
} else {
//Update existing record code here
}
Not OP's answer but as this was the first question that popped up for me in google, Id also like to add that users searching for this might need to reseed their table, which was the case for me
DBCC CHECKIDENT(tablename)
There could be several things causing this and it somewhat depends on what you have set up in your database.
First, you could be using a PK in the table that is also an FK to another table making the relationship 1-1. IN this case you may need to do an update rather than an insert. If you really can have only one address record for an order this may be what is happening.
Next you could be using some sort of manual process to determine the id ahead of time. The trouble with those manual processes is that they can create race conditions where two records gab the same last id and increment it by one and then the second one can;t insert.
Third, you query as it is sent to the database may be creating two records. To determine if this is the case, Run Profiler to see exactly what SQL code you are sending and if ti is a select instead of a values clause, then run the select and see if you have due to the joins gotten some records to be duplicated. IN any even when you are creating code on the fly like this the first troubleshooting step is ALWAYS to run Profiler and see if what got sent was what you expected to be sent.
Make sure if your table doesn't already have rows whose Primary Key values are same as the the Primary Key Id in your Query.

Ruby printing out hash data

I am working on a database that holds records for a school, where the key is the studentID, followed by the values of, first name, last name, major, and catalog year. I am working on the display function, which loops through the users which have been added to the hash. however, my code is not printing out of all the records i have added to the database.
it is only printing out one record listing, rather than my multiple inputted entries.
here is an example of input:
-----------------------------
Student Database Records
-----------------------------
1) Insert new record to database
2) Modify record in database
3) Remove record from database
4) Display record(s) in database
5) Quit
6) Enter choice:
1
-----------------------------
Add Record(s)
-----------------------------
Enter Student Identifcation Number:
32424
Enter First name of Student:
sfsdf
Enter Last name of Student:
sdfsfsf
Enter Major of Student:
sdfsdfs
Enter Catalogue Year:
sdfsfds
Your entry for Student ID 32424 has been added to the database.
------------------------------------------------------------------------
32424: sfsdf, sdfsfsf, sdfsdfs, sdfsfds
------------------------------------------------------------------------
here is my code to add an array to a hash
student_id = gets().chomp
if school_database.sDB.has_key?(student_id)
puts "Student Record Already Existent"
return school_database
end
puts "\nEnter First name of Student: "
first_name = gets().chomp
puts "\nEnter Last name of Student: "
last_name = gets().chomp
puts "\nEnter Major of Student: "
major = gets().chomp
puts "\nEnter Catalogue Year: "
catalogue_year = gets().chomp
puts "\nYour entry for Student ID #{student_id} has been added to the database.\n"
puts "\n------------------------------------------------------------------------"
puts "#{student_id}: #{first_name}, #{last_name}, #{major}, #{catalogue_year}"
puts "------------------------------------------------------------------------\n\n"
store_account_data = first_name + "," + last_name + "," + major + "," + catalogue_year
school_database.sDB[student_id] = [store_account_data]
return school_database
here is the code i am using to loop through my hash to print out the records.
school_database.sDB.each do |key, store_account_data|
puts "\n"
puts "#{key}: #{store_account_data.join(',')}"
positively, I run the .size command, and i discovered that it is adding muliple entries to the hash, however, it is not printing all of them
any ideas?
String’s + method places fairly strict requirements on what can appear on the right-hand side. You need to explicitly call to_s:
puts key + ' : ' + store_account_data.to_s
String interpolation is much more forgiving; it basically calls to_s for you:
puts "#{key} : #{store_account_data}"
Or perhaps you want a more detailed dump:
puts "#{key} : #{store_account_data.inspect}"
Or no brackets:
puts "#{key} : #{store_account_data.join(', ')}"
Or perhaps elements of store_account_data are objects, and you want to just print one property of them:
puts "#{key} : #{store_account_data.map(&:field_to_print).join(', '}"
I would do something like:
def display(database)
database.sDB.each do |key, account|
puts "#{key}: #{account.join(',')}"
end
end
You can use ruby's join method. I believe that's pretty common among languages.

Searching in database from a form returning empty input

I want to do search in my database using some fields filled by a form
but if some fields are left empty i don't want to include them
which kind of query can help me in achieving this??
Currently i am using a query like:
Select * from DATABASE where COLUMN='form_input';
but as my form will return empty it will try and select rows which have null entries but rather i want to this time see a result of all rows in database i.e i want to invalidate the filter by COLUMN='form_input'
As we do not know your server side scripting language -
The psheuducode should be -
if(request['form_input']!=null)
Select * from DATABASE where COLUMN='form_input';
else
Select * from DATABASE;
Also If there are many fields for form_input then we can design
our code something like -
String wherequery = "";
if(request['form_input1']!=null)
{
wherequery = wherequery + " COLUMN='form_input1' ";
}
if(request['form_input2']!=null)
{
wherequery = wherequery + " And "
wherequery = wherequery + " COLUMN='form_input2' ";
}
if(request['form_input3']!=null)
{
wherequery = wherequery + " And "
wherequery = wherequery + " COLUMN='form_input3' ";
}
....
And so on
....
String selectQuery = "";
if(wherequery == "")
{
selectQuery = "Select * from TABLE";
}
else
{
selectQuery = "Select * from TABLE where" + wherequery ;
}
execute (selectQuery);
Please note we are using pseudo code here. We can take the form inputs and concatenate query for each input which is not null.
If we find the concatenated string as blank string, we will select the full table.
Otherwise
we will select with the where clause query.
Hope, this help you out.

Resources