How to print out a specific column from MySQL in java - java

I am trying to print out all the columns that has the same path as the one that i get from an Image. The main problem is that path='path' is read as a string with the value "path" instead of the value that i have in my path-variable. path = path without the '' is not accepted as a value, and therefore i can't print the columns. if i directly insert path='C:\Users....\' here, it prints out the right columns.
public void getImageInfoFromDatabase(Image image) {
String path = image.getFile().getAbsolutePath();
path = path.replace("\\", "\\\\");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection(url, user, pass);
Statement statement = connect.createStatement();
resultSet = statement.executeQuery("SELECT * FROM image_table WHERE path='path'");
while (resultSet.next()) {
int id = resultSet.getInt(1);
String title = resultSet.getString(2);
String path = resultSet.getString(3);
String tags = resultSet.getString(4);
String latitude = resultSet.getString(5);
String longitude = resultSet.getString(6);
java.util.Date timestamp = resultSet.getTimestamp(7);
System.out.println(id + " " + title + " " + path + " " + tags + " " + latitude + " " + longitude + " " + timestamp);
}
} catch (SQLException | ClassNotFoundException e) {
System.out.println("Error. ");
e.printStackTrace();
}
}

I found out that i had to use the setString method from PreparedStatement to input a value at a specific index. The complete functioning code looks like this:
public boolean getImageInfoFromDatabase(Image image) {
boolean success = true;
String string = image.getFile().getAbsolutePath();
string = string.replace("\\", "\\\\");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection(url, user, pass);
PreparedStatement stmt = connect.prepareStatement("SELECT * FROM image_table WHERE path = ?");
stmt.setString(1, string);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt(1);
String title = resultSet.getString(2);
String path = resultSet.getString(3);
String tags = resultSet.getString(4);
String latitude = resultSet.getString(5);
String longitude = resultSet.getString(6);
java.util.Date timestamp = resultSet.getTimestamp(7);
System.out.println(id + " " + title + " " + path + " " + tags + " " + latitude + " " + longitude + " " + timestamp);
success = true;
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
success = false;
}
return success;
}

SELECT * FROM image_table WHERE path='path'

Related

how to solve this "not using PreparedStatement method" problem?

This is query section
#FXML
void dbsave(ActionEvent event) throws SQLException {
String user = parUsertxt.getText();
String first = parFirstNametxt.getText();
String last = parLastNametxt.getText();
String cnic = parCnictxt.getText();
String date = parDatetxt.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String address = parAddresstxt.getText();
String status = parStatustxt.getText();
String province = parProvincetxt.getText();
String district = parDistricttxt.getText();
String tehsil = parTehsiltxt.getText();
String area = parAreatxt.getText();
String phone = parPhonetxt.getText();
String ephone = parEmPhonetxt.getText();
String gender = parGendertxt.getSelectionModel().getSelectedItem();
String father = parFatherNametxt.getText();
String fathercnic = parFatherCNICtxt.getText();
// BinaryStreamValueFactory personimage;// how can i use this to store an image
String query = "INSERT INTO `landrecord`.`parowner` (`UserName`, `FirstName`, `LastName`, `CNIC`, `DateOfBirth`, `Address`, `Status`, `Province`, `Tehsil`, `District`, `Area`, `PhoneNo`, `EmergencyPhoneNo`, `Gender`, `FatherName`, `FatherCNIC`,'ImagePerson') " +
"VALUES ('" + user + "','" + first + "','" + last + "','" + cnic + "','" + date + "','" + address + "','" + status + "','" + province + "','" + tehsil + "','" + district + "','" + area + "','" + phone + "','" + ephone + "','" + gender + "','" + father + "','" + fathercnic + "')";
if (connectionClass.execAction(query)) {
System.out.println("Data Successful Save");
savebtn.getScene().getWindow().hide();
try {
Parent root = FXMLLoader.load(getClass().getResource("parLandRecord.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (IOException ex) {
System.out.print(ex.getLocalizedMessage());
}
}else{
System.out.println("Insertion Failed.");
}
}
This is the button to show image in image view
#FXML
void personCnicbtn(ActionEvent event) throws MalformedURLException {
fileChooser1 = new FileChooser();
fileChooser1.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Select Image","*.png","*.jpg","*.gif"));
File file1 = fileChooser1.showOpenDialog(null);
if (file1 != null){
imageFile1 = file1.toURI().toURL().toString();
Image image1 = new Image(imageFile1);
personCnicImage.setImage(image1);
}else{
System.out.println("image Error");
}
}
this is the code I'm working on Now I need to save an image without using preparedStatement Or if there is a way to use preparedStatement then please tell me how?
If you are storing file into database i recommended store in blob format.it is good to handle.here in code i am simple giving info in your code how to store using prepared statement.
Connection connection = null;
PreparedStatement statement = null;
FileInputStream inputStream = null;
File image = new File("your_file_path_which_is_getting_from_FileChooser");
inputStream = new FileInputStream(image);
/**
* establish connection of database.
*/
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_db", "your_username", "your_pw");
statement = connection.prepareStatement("insert into parowner(UserName,FirstName,LastName,CNIC,DateOfBirth,Address,Status,Province,Tehsil,District,Area,PhoneNo,EmergencyPhoneNo,Gender,FatherName,FatherCNIC,ImagePerson) " + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
statement.setString(1, "UserName");
/**
* set image as byte stream
*/
statement.setBinaryStream(17, (InputStream) inputStream, (int)(image.length()));
statement.executeUpdate();

jdbc application update sql isnt working for me, any ideas

public void Update(String name, String mobile, String email, String car, String model, String year, String color, String plate_no, String plateletters,String gear, String km, String date,String licesnse,String status, String notes){
Connection conn = null;
try{
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("connected");
Statement stmt = (Statement) conn.createStatement();
String ins = "update car"
+ "set Name = '"+name+"' , "
+ "Email = '"+email+"' , "
+ "Car = '"+car+"' , "
+ "Model = '"+model+"' , "
+ "Year = '"+year+"' , "
+ "Color = '"+color+"' , "
+ "Plateno = '"+plate_no+"' , "
+ "Plateletters = '"+plateletters+"' , "
+ "Gearbox = '"+gear+"' , "
+ "Km = '"+km+"' , "
+ "Date = '"+date+"' , "
+ "License = '"+licesnse+"' , "
+ "Status = '"+status+"' , "
+ "Notes = '"+notes+"' "
+ "where Mobile = '"+mobile+"' ";
stmt.execute(ins);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
System.err.println(e);
return;
}
}
**i have tried prepared statment and stmt.executeUpdate(ins); but nothing workes !!
Please help!**
the error :
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= 'ahmed' , Email = 'ahmed#hotmail.com' , Car = 'honda' , Model = 'hondaz' , Yea' at line 1
You need to make sure you add proper space between elements in your SQL query:
String ins = "update car"
should be
String ins = "update car "
A good approach to doing this is to write and execute your SQL in your database query tool (SQL developer, phpMyAdmin, whatever) and make sure your syntax is good before trying to re-write it in Java.
Use a preparedStatement instaed of a Statement.
Connection conn = null;
try{
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
PreparedStatement pstm = conn.prepareStatement(
"update car "
+ "set Name = ? ,"
+ "Email = ? ,"
+ "Car = ? ,"
+ "Model = ? ,"
+ "Year = ? ,"
+ "Color = ? ,"
+ "Plateno = ? ,"
+ "Plateletters = ? ,"
+ "Gearbox = ? ,"
+ "Km = ?,"
+ "Date = ?,"
+ "License = ?, "
+ "Status = ?, "
+ "Notes = ? "
+ "where mobile = ?"
);
pstm.setObject(1, name);
pstm.setObject(2, email);
pstm.setObject(3, car);
pstm.setObject(4, model);
pstm.setObject(5, year);
pstm.setObject(6, color);
pstm.setObject(7, plate_no);
pstm.setObject(8, plateletters);
pstm.setObject(9, gear);
pstm.setObject(10, km);
pstm.setObject(11, date);
pstm.setObject(12, licesnse);
pstm.setObject(13, status);
pstm.setObject(14, notes);
pstm.setObject(15, mobile);
pstm.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}

Inserting records into an Oracle DB using Java

I am getting a missing comma error and I can't seem to figure out what could be causing it, any help would be appreciated.
Table create SQL:
CREATE TABLE APPOINTMENTS (APP_ID NUMBER(38) NOT NULL, I_ID NUMBER(38), DATE_TIME VARCHAR2(50), INSPECTION_TYPE VARCHAR2(30), PRICE VARCHAR2(10), HST VARCHAR2(10), TOTAL VARCHAR2(10), CLIENT_NAME VARCHAR2(40), CLIENT_NUMBER VARCHAR2(15), CLIENT_EXT VARCHAR2(10), CLIENT_EMAIL VARCHAR2(50), CLIENT_NAME2 VARCHAR2(40), CLIENT_NUMBER2 VARCHAR2(15), CLIENT_EXT2 VARCHAR2(10), CLIENT_EMAIL2 VARCHAR2(50), ADDRESS VARCHAR2(100), INTERSECTION VARCHAR2(100), CITY VARCHAR2(40), AGENT_ID NUMBER(38), REF_SOURCE VARCHAR2(30), BUILDING_TYPE VARCHAR2(30), SQUARE_FEET NUMBER(38), LIST_PRICE VARCHAR2(15), LOCKBOX VARCHAR2(40), VACANT VARCHAR2(10), NOTES VARCHAR2(255), BILL_TO VARCHAR2(20), PICTURES_REQUESTED VARCHAR2(10), FLAG VARCHAR2(10), APPROVED VARCHAR2(10), BUILDING_PREMIUM VARCHAR2(10), TRAVEL_PREMIUM VARCHAR2(10), SIZE_PREMIUM VARCHAR2(10), HOLIDAY_PREMIUM VARCHAR2(10), MISC_PREMIUM VARCHAR2(10), INSPECTOR_PAID VARCHAR2(10), COMPANY VARCHAR2(10) NOT NULL, SUGGESTED_RETAIL VARCHAR2(10), SUGGESTED_HST VARCHAR2(10), SUGGESTED_TOTAL VARCHAR2(10), PRIMARY KEY (APP_ID));
Java code to insert and execute:
dc.query = "INSERT INTO HR.APPOINTMENTS (APP_ID,I_ID, DATE_TIME,INSPECTION_TYPE, PRICE, HST, TOTAL, CLIENT_NAME, CLIENT_NUMBER, CLIENT_EXT, CLIENT_EMAIL,CLIENT_NAME2, "
+ "CLIENT_NUMBER2, CLIENT_EXT2, CLIENT_EMAIL2, ADDRESS, INTERSECTION, CITY, AGENT_ID, REF_SOURCE, BUILDING_TYPE, SQUARE_FEET, LIST_PRICE, LOCKBOX, VACANT,"
+ "NOTES, BILL_TO, PICTURES_REQUESTED, FLAG, APPROVED, BUILDING_PREMIUM, TRAVEL_PREMIUM, SIZE_PREMIUM, HOLIDAY_PREMIUM, MISC_PREMIUM, INSPECTOR_PAID,"
+ "COMPANY, SUGGESTED_RETAIL, SUGGESTED_HST, SUGGESTED_TOTAL)"
+ ""
+ "VALUES (" + hNum + "," + inspector + ",'" + date1 + "','" + inspectionType + "','" + price + "','" + hst + "','" + total + "','" + clientName + "','" + clientNumber + "','"
+ clientExt + "','" + clientEmail + "','" + clientName2 + "','" + clientNumber2 + "','" + clientExt2 + "','" + clientEmail2 + "','" + address + "','" + cMIntersection
+ "','" + city + "'," + hNum2 + ",'" + rSource + "','" + bType + "', 1000 ,'" + listPrice + "','" + lockbox + "','" + vacant + "','" + sInformation + "','" + billTo + "','"
+ pRequested + "','" + flagged + "', 'No', 'No', '0' , '0', '0', '0', '0', 'No','" + company + "','" + suggestedPrice + "','" + suggestedhst + "','" + suggestedTotal + "')";
dc.rset = dc.stmt.executeQuery(dc.query);
Here is a more generic approach. You just need to worry about class Oracle below and perhaps add some new entries for Factory method as I only defined a couple for you.
I also coded the actual execute for your PreparedStatement in the Row class, however I never tested that far. Let me know if it works for you (Don't forget to set your database credentials and stuff) ...
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class Oracle {
public static void main(String[] args) {
Row row = new Row("OWNERNAME", "TABLENAME");
row.setDummyValues();
// set your individual column values here as you debug ...
System.out.println( row.getPreparedStatement() );
// for(Column column : row.getColumns()) {
// System.out.println("[" + column.name + "][" + column.type + "][" + column.nullable + "[" + column.value + "]");
// }
}
}
class Column {
int position;
String name;
String type;
boolean nullable;
Object value;
public Column(ResultSet resultSet) throws SQLException {
position = resultSet.getInt("COLUMN_ID");
name= resultSet.getString("COLUMN_NAME");
type= resultSet.getString("DATA_TYPE");
nullable= resultSet.getBoolean("NULLABLE");
value = null;
}
}
class DummyValueFactory {
public static Object createDummyValue(String type, boolean nullable) {
Object value = null;
if(!nullable) {
if(type.contains("CHAR")) {
value = "ABC";
}
else if(type.contains("NUMBER")) {
value = new Integer("123");
}
else if(type.contains("TIMESTAMP")) {
value = new java.sql.Timestamp(System.currentTimeMillis());
}
else {
throw new RuntimeException("CANNOT BUILD A DUMMY VALUE FOR " + type);
}
}
return value;
}
}
class Row {
String owner;
String table;
List<Column> columns = new ArrayList<Column>();
public Row(String ownerName, String tableName) {
owner = ownerName;
table = tableName;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(getMetaDataQuery());
while(resultSet.next()) {
columns.add(new Column(resultSet));
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(resultSet != null) {
resultSet.close();
}
if(statement != null) {
statement.close();
}
if(connection != null) {
connection.close();
}
}
catch (SQLException e) {
statement = null;
connection = null;
}
}
}
public void setDummyValues() {
for(Column column: columns) {
column.value = DummyValueFactory.createDummyValue(column.type, column.nullable);
}
}
public List<Column> getColumns() {
return columns;
}
public Column getColumn(String columnName) {
Column foundColumn = null;
for(Column column: columns) {
if(column.name.equals(columnName)) {
foundColumn = column;
break;
}
}
return foundColumn;
}
public boolean setColumn(String columnName, Object value) {
boolean result = false;
for(Column column: columns) {
if(column.name.equals(columnName)) {
column.value = value;
result = true;
break;
}
}
return result;
}
private final String getMetaDataQuery() {
String SQLString = "SELECT COLUMN_ID,\n";
SQLString += " COLUMN_NAME,\n";
SQLString += " DATA_TYPE,\n";
SQLString += " NULLABLE\n";
SQLString += "FROM ALL_TAB_COLUMNS\n";
SQLString += "WHERE OWNER = '" + owner + "'\n";
SQLString += " AND TABLE_NAME = '" + table + "'\n";
SQLString += "ORDER BY COLUMN_ID";
return SQLString;
}
public String getPreparedStatement() {
int counter = 0;
String SQLString = "INSERT INTO " + owner + "." + table + "(\n";
for(Column column : columns) {
if(counter++ > 0) {
SQLString += ", ";
}
SQLString += "\t" + column.name + "\n";
}
SQLString += ") VALUES (\n";
counter = 0;
for(int index = 0; index < columns.size(); index++) {
if(counter++ > 0) {
SQLString += ", ";
}
SQLString += "\t?\n";
}
SQLString += ")";
return SQLString;
}
public void executeInsert() {
Connection connection = null;
PreparedStatement preparedStatement = null;
String SQLString = getPreparedStatement();
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(SQLString);
for(int index = 0; index < columns.size(); index++) {
preparedStatement.setObject(index, columns.get(index).value);
}
preparedStatement.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(preparedStatement != null) {
preparedStatement.close();
}
if(connection != null) {
connection.close();
}
}
catch (SQLException e) {
preparedStatement = null;
connection = null;
}
}
}
private static final Connection getConnection() throws ClassNotFoundException, SQLException, IOException {
String user = "username";
String password = "password";
String server = "server";
int port = 1234;
String sid = "database";
Connection connection = null;
String url = "jdbc:oracle:thin:#" + server + ":" + port + ":" + sid;
Class.forName("oracle.jdbc.driver.OracleDriver");
java.util.Properties info = new java.util.Properties();
info.put ("user", user);
info.put ("password", password);
info.put ("useFetchSizeWithLongColumn", "true");
connection = DriverManager.getConnection(url, info);
return connection;
}
}

error in java update

if (e.getSource() == btn_updt) {
try {
String str = "img";
int max_avail;
double price;
Frame f = new Frame();
Connection con;
DriverManager
.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:dsnproj", "", "");
Statement s = con.createStatement();
// int mno=Integer.parseInt(txt_contcno.getText());
price = Double.parseDouble(txt_price.getText());
max_avail = Integer.parseInt(txt_qty_avl.getText());
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',desc='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";
System.out.println(qry_up);
s.execute(qry_up);
System.out.println("updated");
// JOptionPane.showMessageDialog(f,
// "Updates Successfully : ","A plain message",JOptionPane.PLAIN_MESSAGE);
} catch (Exception ae) {
System.out.println(ae.getLocalizedMessage());
}
return result;
}
and i got error as:
update category set prod_name='jjhhj',desc='jjjh',photo='img',max_quan_avail=88,cur_price=99.0,per='piece' where p_name='brush' [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
please help me...
Since DESC is a keyword, you must surround it with [].
Use this for your query:
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',[desc]='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";

java-mysql program

i have a table - emp_details in mysql
i want to seatch an employ's id number in java.
if it is in the table , then show all the details of employee.
otherwise display an error message.
how i do this
Using JDBC
Here is an example You can build your solution from it.
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
stmt.close();
}
ResultSet rs1=stmt.executeQuery("SELECT * FROM employee_details where Employee_ID='"+strEmpId+"'");
if(rs1.next()) {
System.out.println("Emp ID : " + rs1.getString(1));
System.out.println("Emp Name : " + rs1.getString(2));
System.out.println("Emp Salary : " + rs1.getString(3));
} else {
System.out.println("Emp ID not found");
}
If you want to know more about SQL just go through HERE

Categories

Resources