Inserting data through GUI into sql server - sql

I'm able to execute sql statements by writing the sql codes (Insert etc) on Eclipse and it is being displayed into sql server correctly. Connection has been done. But what should I do when a user wants to add data through a GUI interface (text field) and the data need to get stored into the database automatically ??
my code in the ADD button, but i'm getting the Error: java.lang.NullPointerException ! Help please..
try {
String pid = ProductID.getText();
String sql = "insert into Products_tbl values (' " +pid + " ')";
// Running the sql query
rs = st.executeQuery(sql);
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Welcome");
}
else if (count > 1) {
JOptionPane.showMessageDialog(null,"Duplicate User Access Denied");
}
else {
JOptionPane.showMessageDialog(null, " User Not Found ");
}
}
catch (Exception ex) {
System.out.println("Error: " + ex);
}

1- Using (' " +pid + " ')" is not safe because SQL injection may occur. Use SqlParameters instead. Please check:
https://www.w3schools.com/sql/sql_injection.asp
2- I am pretty sure something is wrong with the line: rs = st.executeQuery(sql);
Here, I bet the value of st is null. Make sure that your connection variable is defined and set correctly and you created the statement like below:
st = connection.createStatement();
You can also try executeupdate(query) instead of executequery(query) like:
int flag = st.executeUpdate(query);
Ref: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29
3- Please use printStackTrace() method while printing the error in the catch blog, the error message would be more understandable.
System.out.println("Error: " + ex.printStackTrace());

Related

How to solve "ORA-00933 & ORA-00936" in SQL/Oracle?

Im creating a student profile for our project in school and it's my first time to make this.
This is my query for my jTable (mouseclicked) I've created in netbeans
int row = jTable1.getSelectedRow();
String tc = jTable1.getModel().getValueAt(row, 0).toString();
try {
String query ="select * from CAREPOINT_STUDENT where NAME="+tc+" ";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
rs = (OracleResultSet) pst.executeQuery();
if(rs.next()){
String NAME_ID = rs.getString("NAME");
String AGE_ID = rs.getString("AGE");
String ADDRESS_ID = rs.getString("ADDRESS");
String NUM_ID = rs.getString("NUM");
String COURSE_ID = rs.getString("COURSE");
String SPECIAL_ID = rs.getString("SPECIAL");
String SCHOOL_ID = rs.getString("SCHOOL");
String DOWNPAY_ID = rs.getString("DOWNPAY");
String DISCOUNT_ID = rs.getString("DISCOUNT");
String BALANCE_ID = rs.getString("BALANCE");
String REVSCHED_ID = rs.getString("REVSCHED");
String EMAIL_ID = rs.getString("EMAIL");
NAME.setText(NAME_ID);
AGE.setText(AGE_ID);
ADDRESS.setText(ADDRESS_ID);
NUM.setText(NUM_ID);
COURSE.setText(COURSE_ID);
SPECIAL.setText(SPECIAL_ID);
SCHOOL.setText(SCHOOL_ID);
DOWNPAY.setText(DOWNPAY_ID);
DISCOUNT.setText(DISCOUNT_ID);
BALANCE.setText(BALANCE_ID);
REVSCHED.setText(REVSCHED_ID);
EMAIL.setText(EMAIL_ID);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
When I run the program and tried to click the data (A Student Profile like name,age,school, etc..) that I created and printed inside the jtable (mouseclicked), I get this problem "ORA-00933: SQL command not properly ended"
Aside from that, I also have another problem which I created 2 jbutton called "DELETE" which means it will delete the data(Student profile) that I filled up and "UPDATE" which means to reedit the data(Student profile) that I filled up.
this is the query of my "DELETE" jbutton in netbeans
try {
String query;
query = "DELETE FROM CAREPOINT_STUDENT where NAME="+NAME.getText()+" ";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Successfully deleted!");
fetch();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
and this is the query of my "UPDATE" jbutton in netbeans
try {
String query;
query = "update CAREPOINT_STUDENT set AGE=?,ADDRESS=?,NUM=?,COURSE=?,SPECIAL=?,SCHOOL=?,DOWNPAY=?,DISCOUNT=?,BALANCE=?,REVSCHED=?,EMAIL=? where NAME="+NAME.getText()+"";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.setString(1,AGE.getText());
pst.setString(2,ADDRESS.getText());
pst.setString(3, NUM.getText());
pst.setString(4, COURSE.getText());
pst.setString(5, SPECIAL.getText());
pst.setString(6, SCHOOL.getText());
pst.setString(7, DOWNPAY.getText());
pst.setString(8, DISCOUNT.getText());
pst.setString(9, BALANCE.getText());
pst.setString(10, REVSCHED.getText());
pst.setString(11, EMAIL.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Successfully updated!");
fetch();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
when I run the program and click those 2 buttons, I get the same problem "ORA-00936: missing expression"
I really appreciate and I hope that somebody would help me to fix this problem. So that I can gain some little knowledge about sql/oracle.
Sorry for my bad english.
Avoid concatenating parameters as strings; use prepared statements.
Otherwise you'll run in all kind of troubles, like escaping issues for special characters, SQL Injection, etc.
For example, a safer way of running your SQL statement could be:
String query = "select * from CAREPOINT_STUDENT where NAME = ?";
pst = (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.setString(1, tc);
rs = (OracleResultSet) pst.executeQuery();
Note: Assembling a SQL statement as a string is still useful for cases when you want to do some dynamic SQL. Even then, use ? for parameters and apply them as shown above.
You may need some extra single quotes so you query will read:
select * from CAREPOINT_STUDENT where NAME='Entered name';
Adjust your code:
String query ="select * from CAREPOINT_STUDENT where NAME='"+tc+"' ";

Searching SQL for specific CHAR

I have a database table were a column holds multiple strings. They are holding License Plate numbers. If I search for 1 il get the first registration it finds with a one. I want to set it so that I must enter the full string and if I don't it should say not found. Here is my code. I'm sure its just the SQL command that needs altering for this.
public Car getCar(String searchLicense) {
Car foundCar = new Car();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
resultSet = statement
.executeQuery("select * from eflow.registration where cLicense like '%" + searchLicense + "%'");
while (resultSet.next()) {
foundCar = new Car(resultSet.getInt("cID"), resultSet.getString("cLicense"),
resultSet.getInt("cJourneys"), resultSet.getString("cUsername"),
resultSet.getString("cPassword").toString());
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return foundCar;
}
If you need the exact string, you will need to remove the '%' in the LIKE filter.
Your code should be:
cLicense like '" + searchLicense + "'
The '%' wildcard put before and after the parameter you have, enables you to search for any string containing the searchLicense value in the middle, without checks of what is before or after that string.
You should be using parameterized queries. Bobby Tables: A guide to preventing SQL injection
Then use = instead of like.
select * from eflow.registration where cLicense = #searchLicense

jdbc and processing output using Jakarta Commons Math

Using jdbc I am querying my database of ambulance response times. My goal is to take the output and process it into statistics using Jakarta Commons Math library. So far I am successful in querying my database and outputting the response times to the console. My next step is to process this output statistically, such as mean, medians, mode, etc. This is where I am stuck. Shown below is my code.
package javaDatabase;
import java.sql.*;
import org.apache.commons.math3.stat.StatUtils;
public class javaConnect3
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
try
{
conn = DriverManager
.getConnection("jdbc:sqlserver://myServerAddress;database=myDatabase;integratedsecurity=false;user=myUser;password=myPassword");
stmt = conn.createStatement();
String strSelect = "SELECT M_SecondsAtStatus FROM MManpower WHERE M_tTime > 'august 25, 2014' AND M_Code = 'USAR'";
ResultSet rset = stmt.executeQuery(strSelect);
while (rset.next())
{
int values = rset.getInt("M_SecondsAtStatus");
System.out.println(values);
}
// I am hoping to derive useful statistics from my database, such as the following.
// this uses Jakarta Commons Math
// System.out.println("min: " + StatUtils.min(values));
// System.out.println("max: " + StatUtils.max(values));
// System.out.println("mean: " + StatUtils.mean(values));
// System.out.println("product: " + StatUtils.product(values));
// System.out.println("sum: " + StatUtils.sum(values));
// System.out.println("variance: " + StatUtils.variance(values));
} catch (SQLException ex)
{
ex.printStackTrace();
} finally
{
try
{
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
}
}
}
An error message pops up in Eclipse and the variable "values" is red underlined; "values cannot be resolved to a variable".
I am not sure how to get this to work. I don't understand how to output my ambulance response times from the database into something Apache Commons math will understand.
How can I get Apache Commons math to take the output from my database and generate a statistical result?
You need something like this:
List<Double> values = new ArrayList<Double>();
while (rset.next()) {
values.add(rset.getInt("M_SecondsAtStatus"));
}
double mean = StatsUtils.mean(values.toArray(new Double [](values.size()));
It's likely that you could query the database for statistics. The name of the method depends on your database:
SELECT avg(M_SecondsAtStatus)
FROM MManpower
WHERE M_tTime > 'august 25, 2014'
AND M_Code = 'USAR'
I'd say the second one is more efficient, because you don't have to transfer all those values to the Java JVM to do the same calculation that the database can do for you.
Another alternative is to use a DescriptiveStatistics object to collect all the data and then use it to compute the summary statistics you need. Using it alleviates the need for doing all explicit type casting and conversion:
DescriptiveStatistics ds = new DescriptiveStatistics();
while(rset.next()) {
int observation = rset.getInt("M_SecondsAtStatus");
ds.addValue(observation);
}
System.out.println("min: " + ds.getMin());
System.out.println("max: " + ds.getMax());
...

get data from resultset after the execution of sql query in netbeans

I have created a table register in SQL with field username. In the JFrame when a user enters username there is a JButton for checking the username availability. For this I have used the code below:
String sqlstmt = "select username from register where username='" +
jTextField1.getText() + "'";
try {
st = con.prepareStatement(sqlstmt);
stmt = con.createStatement();
rs = st.executeQuery(sqlstmt);
if (rs.next()) {
JOptionPane.showMessageDialog(null,"found");
} else {
JOptionPane.showMessageDialog(null,"not found");
}
} catch(SQLException e) {
JOptionPane.showMessageDialog(null,"sql error");
}
when executing this query, it is seen that data is empty. Or if I put rs.getString("username") inside the if (rs.next), it shows the "sql error" message.
You're mixing Statements and PreparedStatements here.
The best approach here would probably be to use a PreparedStatement, which would take care of any funky characters from your input, and offer protection against SQL injection:
// SQL statement to prepare.
// Note the lack of single quotes (') in the parameter
String sqlstmt= "select username from register where username = ?";
// Prepare the statement
PreparedStatement st = con.prepareStatement(sqlstmt);
// Bind the argument
st.setString(1, jTextField1.getText());
// Execute
ResultSet rs = st.executeQuery();
// Rest of the code to handle results...
Note:
This example omits error handling (e.g., try-catch constructs) in favor of clarity.

Column is not indexed even though it is. PreparedStatement inside

I'm really struggling with a bug that did not appear on my dev environment, only once deployed in test.
I'm using a prepared Statement to run around 30 000 query in a row. The query check for the similarity of a string with what's in our database, using the oracle fuzzy method.
The column checked is indexed, but, don't know why, it fails randomly after some iterations, saying that index does not exists.
I don't understand what's going on, as the index really exists. My method never rebuild or delete the index so there is no reason for this error to appear ...
public List<EntryToCheck> checkEntriesOnSuspiciousElement(List<EntryToCheck> entries, int type,int score, int numresults, int percentage) throws Exception {
Connection connection = null;
PreparedStatement statementFirstName = null;
PreparedStatement statementLastname = null;
int finalScore = checkScore(score);
int finalNumResults = checkNumResults(numresults);
int finalPercentage = checkPercentage(percentage);
try {
connection = dataSource.getConnection();
StringBuilder requestLastNameOnly = new StringBuilder("SELECT SE.ELEMENT_ID, SE.LASTNAME||' '||SE.FIRSTNAME AS ELEMENT, SCORE(1) AS SCORE ");
requestLastNameOnly.append("FROM BL_SUSPICIOUS_ELEMENT SE ");
requestLastNameOnly.append("WHERE CONTAINS(SE.LASTNAME, 'fuzzy({' || ? || '},' || ? || ',' || ? || ', weight)', 1)>? ");
requestLastNameOnly.append((type > 0 ? "AND SE.ELEMENT_TYPE_ID = ? " : " "));
requestLastNameOnly.append("ORDER BY SCORE DESC");
statementLastname = connection.prepareStatement(requestLastNameOnly.toString());
for (EntryToCheck entryToCheck : entries) {
ResultSet rs;
boolean withFirstName = (entryToCheck.getEntryFirstname() != null && !entryToCheck.getEntryFirstname().equals(""));
statementLastname.setString(1, entryToCheck.getEntryLastname().replaceAll("'","''"));
statementLastname.setInt(2, finalScore);
statementLastname.setInt(3, finalNumResults);
statementLastname.setInt(4, finalPercentage);
if(type > 0){
statementLastname.setInt(5, type);
}
System.out.println("Query LastName : " + entryToCheck.getEntryLastname().replaceAll("'","''") );
rs = statementLastname.executeQuery();
while (rs.next()) {
Alert alert = new Alert();
alert.setEntryToCheck(entryToCheck);
alert.setAlertStatus(new AlertStatus(new Integer(AlertStatusId.NEW)));
alert.setAlertDate(new Date());
alert.setBlSuspiciousElement(new BlSuspiciousElement(new Integer(rs.getInt("ELEMENT_ID"))));
alert.setMatching(rs.getString("ELEMENT") + " (" + rs.getInt("SCORE") + "%)");
entryToCheck.addAlert(alert);
}
}
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
finally {
DAOUtils.closeConnection(connection, statementLastname);
}
return entries;
}
Really don't know what to look at ...
Thanks !
F
I never used Oracle text tables but my advice is:
Make sure that no one else is executing DDL statements on the table simultaneously.
Also, make sure that, index you have is context index.
Create an index for your column where you want to apply search
........................................
CREATE INDEX "MTU219"."SEARCHFILTER" ON "BL_SUSPICIOUS_ELEMENT " ("LASTNAME")
INDEXTYPE IS "CTXSYS"."CONTEXT" PARAMETERS ('storage CTXSYS.ST_MTED_NORMAL SYNC(ON COMMIT)');
..........................................