insert row before the first row - mysql

I'm trying to write to a database at the beginning so that the new row is the first row.The code i have here will write to it, but it won't start before the first row. I've tried using resultset and tried to use beforeFirst(), but it tells me that i can't use either one. I'm stumped as to how to do it. any help would be appreciated! :D
String host = "jdbc:derby://localhost:1527/Scores";
String uName = "root";
String uPass= "root";
Connection con = DriverManager.getConnection( host, uName, uPass );
String SQLw = "INSERT into ROOT.HISCORES (Intials,Score) values (?,?)";
pst = con.prepareStatement(SQLw);
pst.setString(1,jtxtIntials.getText());
pst.setString(2,Score);
pst.execute();

The rows in a relational database are indeed stored in some physical order, but using SQL, you are unable to control this order directly. Thinking of the order in which the rows are physically stored is absolutely against the philosophy of SQL, and hence such a functionality is not included in it.
If you are interested in ordering your rows, you should add an extra attribute, for numbering the rows, by example, and use the ORDER BY clause whenever retrieving them, as mentioned in the comments.

Related

Populating Autocomplete list with new tags

I'm using Lucee 5.x and Maria DB (MySQL).
I have a user supplied comma delimited list. I need to query the database and if the item isn't in the database, I need to add it.
user supplied list
green
blue
purple
white
database items
black
white
red
blue
pink
orange
lime
It is not expected that the database list would grow to more than 30 items but end-users always find 'creative' ways to use the tools we provide them.
So using the user supplied list above, only green and purple should be added to the database.
Do I compare the user supplied list against the database items or vice versa? Would the process change if the user supplied list count exceeds what is in the database (meaning if the user submits 10 items and the database only contains 5 items)? I'm not sure which loop is the better way to determine which items are new. Needs to be in cfscript and I'm looking at the looping options as outlined here (https://www.petefreitag.com/cheatsheets/coldfusion/cfscript/)
FOR Loop
FOR IN Loop (Array)
FOR IN Loop (Query)
I tried MySQL of NOT IN but that left me with the existing database values in addition to the new ones. I know this should be simple and I'm over complicating this somewhere and/or am too close to the problem to see the solution.
You could do this:
get a list with existing items from database
append user supplied list
remove duplicates
update db if items were added
<cfscript>
var userItems = '"green","blue","purple","white"';
var dbItems = '"black","white","red","blue","pink","orange","lime"';
var result = ListRemoveDuplicates( ListAppend(dbItems, userItems));
if (ListLen(result) neq ListLen(dbItems)) {
// update db
}
</cfscript>
Update (only new items)
<cfscript>
var userItems = '"green","blue","purple","white"';
var dbItems = '"black","white","red","blue","pink","orange","lime"';
var newItems = '';
ListEach(userItems, function (item) {
if (not ListFind(dbItems, item)) {
newItems = ListAppend(newItems, item);
}
})
</cfscript>
trycf.com gist:
(https://trycf.com/gist/f6a44821165338b3c10b7808606979e6/lucee5?theme=monokai)
Again, since this is an operation that the database can do, I'd feed the input data to the database and then let it decide how to deal with multiple keys. I don't recommend using CF to loop through your values to check them and then doing the INSERT. This will require multiple trips to the database and then processing on the application server that isn't really needed.
My suggestion is to use MariaDB's INSERT....ON DUPLICATE KEY UPDATE... syntax. This will also require that whatever field you are trying to insert on actually has a UNIQUE constraint on it. Without that constraint, then your database itself doesn't care if you have duplicate data, when can cause its own set of issues.
For the database, we have
CREATE TABLE t1 (mycolor varchar(50)
, CONSTRAINT constraint_mycolor UNIQUE (mycolor)
) ;
INSERT INTO t1(mycolor)
VALUES ('black'),('white'),('red'),('blue'),('pink'),('orange'),('lime')
;
The ColdFusion is:
<cfscript>
myInputValues = "green,blue,purple,white" ;
myQueryValues = "" ;
function sanitizeValue ( String inVal required ) {
// do sanitization stuff here
var sanitizedInVal = arguments.inVal ;
return sanitizedInVal ;
}
myQueryValues = myInputValues.listMap(
function(i) {
return "('" & sanitizeValue(i) & "')" ;
}
) ;
// This will take parameterization out of the cfquery tag and
preform sanitization and validation before building the
query string.
myQuery = new query();
myQuery.name = "myQuery";
myQuery.setDataSource("dsn");
sqlString = "INSERT INTO t1(mycolor) VALUES "
& myQueryValues
& " ON DUPLICATE KEY UPDATE mycolor=mycolor;"
;
myQuery.setSQL(sqlString);
myQueryResult = myQuery.execute().getResult();
</cfscript>
First, build up your input values (myInputValues). You'll want to do validation and sanitization on them to prevent nastiness from entering your database. I created a sanitizeValue function to be the placeholder for the sanitization and validation operations.
myQueryValues will become a string list of the values in the proper format that we will use to insert into the database.
Then we just build up a new query(), using myQueryValues in the sqlString to get our query. Again, since we are building a string for multiple values to INSERT, I don't think there's a way to user queryparam for those VALUES. But since we cleaned up our string earlier, it should do much of what cfqueryparam does anyway.
We use MariaDB's INSERT INTO .... ON DUPLICATE KEY UPDATE ... syntax to only insert unique values. Again, this requires that the database itself has a constraint to prevent duplicates in whatever column we're inserting.
For a demo: https://dbfiddle.uk/?rdbms=mariadb_10.2&fiddle=4308da3addb9135e49eeee451c6e9e58
This should do what you're looking to do without beating up on your database too much. I don't have a Lucee or MariaDB server set up to test, so you'll have to give it a shot and see how it performs. I don't know how big your database is or will become, but this should still query pretty quickly.

Avoid data for being inserted into new rows in mysql database

I have saved a source code .ccp type file under column 'file' in file_details table in a mysql database. It is done not by using a program but by directly inserting through localhost/phpmyadmin interface. The type of the data field is BLOB. Then by accessing saved codes I am calculating the number of spaces of each source codes and I want to insert the values to the database column called 'spaces' in the same table. Here I have given the query that I used.
Statement stmt = conn.createStatement();
Statement count_to_db=conn.createStatement();
String query = "SELECT prog_num,file FROM file_details";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String file_content = rs.getString("file");
CalculatingSpaces calSpaces = new CalculatingSpaces();
String num_of_Spaces= calSpaces.CalculatingSpaces(rs, pw, file_content);
int spaces=Integer.parseInt(num_of_Spaces);
String space_query="INSERT INTO file_details(spaces) VALUES ('"+spaces+"')";
count_to_db.executeUpdate(space_query);
}
But when I am inserting the spaces they are inserted to a new row but not for the same row where I have uploaded the BLOB files. Is there any way to insert the number of spaces in-front of the BLOB files which spaces related to.
PS : So the problem is Can't I insert data column by column to a database?
If you're adding your table row for the first time, you'll have to use the SQL INSERT command.
If you want to update an existent row, you have to use the SQL UPDATE command.
Don't forget that you need to know which row(s) you want to UPDATE, so you'll also need to define a way to uniquely identify your rows (aka the Primary Key).
See http://dev.mysql.com/doc/refman/5.0/en/update.html for details

How to query database if we need to query with an array of id's in jsp?

After selecting some products a user clicked on proceed button. Now I need to display the selected data on next page. I was successful in getting the id's of selected data using the following code.
String[] array = request.getParameterValues("arrayid");
Now I need to query mysql database using "select * from table where id=?"
I can use this query in a loop. But is there any other or a better way to do this?
Use IN keyword while selecting as select * from table where id IN(comma separated ids)
String[] array = request.getParameterValues("arrayid");
String sql = "SELECT * FROM TABLENAME WHERE id IN ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setArray(1,con.createArrayOf("CHAR", array));
If your question is how to query for a set of IDs in a table, the other answers correctly refer you to SQL's IN keyword. However if you're asking specifically how to do it in Java, JDBC's PreparedStatement, which is the generally recommended way of executing queries in Java, does not make constructing these IN statements easy. I posted a suggested way to address this issue reasonably cleanly here: Can PreparedStatement.addBatch() be used for SELECT queries?

Sql Query LIKE not working

Hi i have trying to do a query, that receives the value on a querystring, but is not working i think the query it self is no good. could you help me?
So i receive the query on
<%String detalhe = request.getParameter("value");%>
I wont put connections and stuff, because they work with other querys, so the problem are not the connections.
// sql query to retrieve values from the specified table.
String QueryString = "SELECT * FROM ebooko.dadoslivros WHERE Autor LIKE '%"+detalhe+"%'
OR ano LIKE '%"+detalhe+"%'";;
rs = statement.executeQuery(QueryString);
It simply cannot retrive the value, i'm querying.
Adicional info:
Table: dadoslivros
Columns that i need to compare the value: Autor, ano.
for example when i run the Href the value that is passed is: Jules%Verne (i gess it changes SPACES with '%'.
Use URLDecoder#decode() to decode the parameters in the query string.
You should also consider using a PreparedStatement to prevent SQL injection attacks.
I solved it changing the query:
String QueryString = "SELECT * FROM dadoslivros WHERE (Data LIKE '%"+detalhe+"%') OR (Autor LIKE '%"+detalhe+"%')";;
maybe it can help another person ;)

mysql insert statement is inserting a blank row instead of the data

I am trying to add new users to my database. For some reason while using the same exact statement in two different scripts and trying to debug, mysql inserts a blank row instead of the actual data if I try to run the query from the php script in which I need it to run from.
On the other hand, when I try to run that exact query in from a random php script, passing the same exact variables (using session variables) to the database, it inserts the data into the database as it should with no problems. I have not idea how to fix such a problem and have been trying for quite a while now. I would greatly appreciate any advice on what I could do to fix this problem.
$usr_email = $_SESSION['email'];
$usr_company_name = $_SESSION['compame'];
$usr_city = $_SESSION['city'];
$usr_state = $_SESSION['state'];
$usr_phone = $_SESSION['phone'];
$usr_password = $_SESSION['password'];
$usr_first = $_SESSION['first'];
$usr_last = $_SESSION['last'];
mysql_query("INSERT INTO users (id, email, compname, city, state, phone, password, first, last)
VALUES('','$usr_email','$usr_company_name','$usr_city','$usr_state','$usr_phone','$usr_password','$usr_first','$usr_last')",$conn);