Hi at now i am programming with Java and wanting to insert some value to specific column choosen. Also, i want to add it in parameter similar with C#:
example:
SqlCommand cmdb = new SqlCommand("insert into Assignment1(textname,person,date,text)
values (#textName,#person,#date,#text)", con);
cmdb.Parameters.AddWithValue("#textname", textPathLabel.Text);
cmdb.Parameters.AddWithValue("#person", personNameTB.Text);
cmdb.Parameters.AddWithValue("#date", DateTime.Now);
cmdb.Parameters.AddWithValue("#text", theBytes);
What you need is to use PreparedStatement in Java. With the example that you've, the corresponding PreparedStatement would look something like this:
PreparedStatement ps = connection.prepareStatement("insert into Assignment1(textname,person,date,text) values(?,?,?,?)");
You would then use the appropriate ps.setXX() methods to set the appropriate values for the parameters that you've defined and then call ps.executeUpdate() to execute the call to the database.
The "JDBC(TM) Database Access" would be a good place to start learning about how to use or execute common SQL statements, and perform other objectives common to database applications.
Related
I am trying to build a class using SQLiteOpenHelper. I would like to get an execSQL sentence in dynamic form. For example, I want to record some java line codes in a SQL database and use them to execute those lines.
Example:
This is de correct form
db.execSQL("insert into "+tabla+" values ("+idname+",'"+name+"',owner '"+owner+"')");
And I would like use like this. The result of query would be
insert into "+tabla+" values ("+idname+",'"+name+"',owner '"+owner+"')
That result would be used like...
db.execSQL(query);
Put on variable like this
String myQuery = "insert into "+tabla+" values ("+idname+",'"+name+"',owner '"+owner+"')"
Use your variable myQuery where you want, as follow
db.execSQL(myQuery);
I'm writing a webpage that takes input from a form, sends it through cgi to a java file, inserts the input into a database through sql and then prints out the database. I'm having trouble inserting into the database using variables though, and I was wondering if anyone would be able to help me out.
String a1Insert = (String)form.get("a1");
String a2Insert = (String)form.get("a2");
This is where I get my variables form the form (just believe that it works, there's a bunch more back end but I've used this before and I know it's getting the variables correctly).
String dbURL = "jdbc:derby://blah.blahblah.ca:CSE2014;user=blah;password=blarg";
Connection conn = DriverManager.getConnection(dbURL);
Statement stmt = conn.createStatement();
stmt.executeUpdate("set schema course");
stmt.executeUpdate("INSERT INTO MEMBER VALUES (a1Insert, a2Insert)");
stmt.close();
This is where I try to insert into the databse. It give me the error:
Column 'A1INSERT' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'A1INSERT' is not a column in the target table.
If anyone has any ideas that would be lovely ^.^ Thanks
java.sql.Statement doesn't support parameters, switching to java.sql.PreparedStatement will allow you to set parameters. Replace the parameter names in your SQL with ?, and call the setter methods on the prepared statement to assign a value to each parameter. This will look something like
String sql = "INSERT INTO MEMBER VALUES (?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "a1");
stmt.setString(2, "a2");
stmt.executeUpdate();
That will execute the SQL
INSERT INTO MEMBER VALUES ('a1', 'a2')
Notice the parameter indexes start from 1, not 0. Also notice I didn't have to put quotes on the strings, the PreparedStatement did it for me.
Alternatively you could keep using Statement and create your SQL string in Java code, but that introduces the possibility of SQL injection attacks. Using PreparedStatement to set parameters avoids that issue by taking care of handling quotes for you; if it finds a quote in the parameter value it will escape it, so that it will not affect the SQL statement it is included in.
Oracle has a tutorial here.
I have been given an oracle procedure with the in out parameter %rowtype,like:
CREATE OR REPLACE PROCEDURE cleansing(
io_user IN OUT USER%rowtype
)
IS
BEGIN
--some pl/sql code
END cleansing;
USER is a table with more than 100 columns, I want to call the procedure by Java.
I can't change the procedure, because they are already used by other project.
I can't add procedure to database, because I don't have the permission to do it.
I google it, but can't find a good way to handle this.
what I want to do is:
1. pass the parameter.
2. get the parameter. some java demo code:
String sql = "{call cleansing(?)}";
try {
dbConnection = getDBConnection();
callableStatement = dbConnection.prepareCall(sql);
callableStatement.setXXX()//I don't know
callableStatement.registerOUTParameter(1, //I don't know the type.);
can anyone help me and give some demo code? no change to database and in out parameter mapping with java
This is possible but it's not really straightforward. You have to create something of type USER%ROWTYPE at runtime and use that to call your stored procedure. Take a look here for details.
To get output values as well, you have to do something extra, along the line of Sumit's comment. Basically, after your procedure call, you open a cursor that selects the relevant data from the USER parameter.
So you get a database statement as follows (pseudocode):
string sql =
"declare
user_param user%rowtype;
begin
-- Set necessary parameters
user_param.col0 := :p0In;
user_param.col1 := :p1In;
...
-- Call procedure.
cleansing(io_user => user_param);
-- Read necessary output values into cursor.
open :pOut for select user_param.col99 as col99
user_param.col98 as col98
...
from dual;
end;"
You call this entire statement the usual way, but you register a cursor out parameter (unfortunately, Java is a very long time ago for me so I'm not sure on the exact syntax).
callableStatement.registerOutParameter("pOut", OracleTypes.CURSOR);
...
callableStatement.execute();
...
ResultSet rs = (ResultSet) callableStatement.getObject("pOut");
// Read from result set.
EDIT: I turned this into a blogpost. Code examples are in C# but the idea is the same.
I want to batch up multiple types of database calls in one PreparedStatement. Is this possible?
Is there anyway to do something like
PreparedStatement pstmt = connection.prepareStatement("?");
where the ? can either be INSERT INTO MY_TABLE VALUES(1,2,3,4) or it could be UPDATE MY_TABLE, SET MY_VAL='1' WHERE MY_VAL IS NULL
Or do I always need to specify a table and action for my prepared statement?
Java will not allow you add only ? in preparedstatement string parameter, as it expects the ? for the place holder only for the parameters to the give SQL.
For your case, you may have to have 2 prepared statement objects, and in loop through, you can make a decision which one to call. So it would be something like below:
PreparedStatement insertPstmt = connection.prepareStatement("INSERT INTO MY_TABLE VALUES(?,?,?,?)");
PreparedStatement updatePstmt = connection.prepareStatement("UPDATE MY_TABLE, SET MY_VAL=? WHERE MY_VAL IS NULL");
While (<condition>) {
If (<insert condition>) {
// use insert pstmt and add batch
} else {
// use update pstmt and add batch
}
}
insertPstmt.executeBatch();
updatePstmt.executeBatch();
if you have any insert , which has dependency on the update, you might execute the batches accordingly. This will make sure that the update will work correctly. I would think of executing insert first, as they might not depend on update.
On a PreparedStatement, after binding the variables for the first execution, call
pstmt.addBatch();
then bind the variables for the next, and each time calling addBatch().
Then, when you're done adding batches you execute the bacth by alling
pstmt.executeBatch();
See :
http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#addBatch%28%29
and
http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeBatch%28%29
BTW : injecting the entire statment into a variable won't work. This batch mechanism exists to reuse the same statement binding different variables each time.
Insert and Update commands don't return any data that has to be processed. If you want to do just things like in your examples, you can simply run a non executing query command and provide a concatenated string of all your sql strings separated by a semicolon.
"INSERT INTO MY_TABLE VALUES(1,2,3,4)" + ";" +"UPDATE MY_TABLE, SET MY_VAL='1' WHERE MY_VAL IS NULL" + ";" +...
You don't need to prepare the statement in that case and also wouldn't receive any performance gain by doing so.
String link = "http://hosted.ap.org";
I want to find whether the given url is already existing in the SQL DB under the table name "urls". If the given url is not found in that table i need to insert it in to that table.
As I am a beginner in Java, I cannot really reach the exact code.
Please advise on this regard on how to search the url in the table.
I am done with the SQL Connection using the java code. Please advise me on the searching and inserting part alone as explained above.
PreparedStatement insert = connectin.preparedStateme("insert into urls(url) vlaues(?)");
PreparedStatement search = connectin.preparedStateme("select * from urls where url = ?");
search.setString(1, <your url value to search>);
ResultSet rs = search.executeQuery();
if (!rs.hasNext()) {
insert.setString(1, <your url value to insert>);
insert.executeUpdate();
}
//finally close your statements and connection
...
i assumed that you only have one field your table and field name is url. if you have more fields you need to add them in insert query.
You need to distinguish between two completely separate things: SQL (Structured Query Language) is the language which you use to communicate with the DB. JDBC (Java DataBase Connectivity) is a Java API which enables you to execute SQL language using Java code.
To get data from DB, you usually use the SQL SELECT statement. To insert data in a DB, you usually use the SQL INSERT INTO statement
To prepare a SQL statement in Java, you usually use Connection#prepareStatement(). To execute a SQL SELECT statement in Java, you should use PreparedStatement#executeQuery(). It returns a ResultSet with the query results. To execute a SQL INSERT statement in Java, you should use PreparedStatement#executeUpdate().
See also:
SQL tutorial
JDBC tutorial