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

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();

Related

How to print out a specific column from MySQL in 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'

How to insert into database from netbeans

Im trying to insert a new "elev" into my table, Im struggling with the query, the variables "id" and "sovsal" are integers. How is the query supposed to look like?
try {
String nextID = db.getAutoIncrement("elev", "elev_id");
angeElevID.setText(nextID);
String id = angeElevID.getText();
String sovsal = angeSovsal.getText();
String efternamn = angeEfternamn.getText();
String fornamn = angeFornamn.getText();
db.insert("INSERT INTO ELEV values('" + id + "','" + fornamn + "','" + efternamn + "'," + sovsal + ")");
JOptionPane.showMessageDialog(null, "En ny elev har lagts till");
} catch (InfException e) {
JOptionPane.showMessageDialog(null, "något blev fel");
}
So the query is like
db.insert("INSERT INTO ELEV (tableElement1, tableElement2,tableElement3, tableElement4) values('"+id+"','"+fornamn+"','"+efternamn+"',"+sovsal+")");
Where the tableElements are the names in the database

Saving data using SQL on android

public void createDatabase(){
try {
Class.forName("org.sqlite.JDBC").newInstance();
Connection connection = DriverManager.getConnection("jdbc:sqlite:occDatabase.db");
Statement statement = connection.createStatement();
String sqlStatement = "CREATE TABLE 'Player_Data' (" +
"'userMoney' TEXT," +
"'oysters' TEXT," +
"'clams' TEXT," +
"'cockles' TEXT," +
"'oysterPrice' TEXT," +
"'clamPrice' TEXT," +
"'cocklePrice' TEXT," +
"'oysterMod' TEXT," +
"'clamMod' TEXT," +
"'cockleMod' TEXT," +
"'cartPrice' TEXT," +
"'fishStandPrice' TEXT," +
"'storePrice' TEXT," +
"'superMarketPrice' TEXT," +
"'cartAmount' TEXT," +
"'fishStandAmount' TEXT," +
"'storeAmount' TEXT," +
"'superMarketAmount' TEXT," +
");";
statement.execute(sqlStatement);
connection.commit();
statement.close();
connection.close();
} catch (Exception e){
}
}
public void writeToDatabase(){
try{
clearData();
createDatabase();
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:occDatabase.db");
Statement statement = connection.createStatement();
String sqlStatemnt = "INSERT INTO Player_Data(userMoney,oysters,clams,cockles,oysterPrice,clamPrice,cocklePrice,oysterMod,clamMod,cockleMod" +
",cartPrice,fishStandPrice,storePrice,superMarketPrice,cartAmount,fishStandAmount,storeAmount,superMarketAmount) " +
"VALUES('" + MainActivity.userMoney + "', '"+ GatheringSystem.oysters +"', '" + GatheringSystem.clams +"', '" + GatheringSystem.cockles +"'," +
" '" + Modifiers.oysterPrice +"', '" + Modifiers.clamPrice +"', '" + Modifiers.cocklePrice +"', '" + Modifiers.oysterMod +"', '" + Modifiers.clamMod +"', '" + Modifiers.cockleMod +
"', '" + MainActivity.cartPrice +"', '" + MainActivity.fishStandPrice +"', '" + MainActivity.storePrice +"', '" + MainActivity.superMarketPrice +"', '" + MainActivity.cartAmount +"'," +
" '" + MainActivity.fishStandAmount +"', '" + MainActivity.storeAmount +"', '" + MainActivity.superMarketAmount +"')";
statement.execute(sqlStatemnt);
connection.commit();
statement.close();
connection.close();
}catch (Exception e){
}
}
public void readFromDatabase(){
Connection connection = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC").newInstance();
connection = DriverManager.getConnection("jdbc:sqlite:occDatabase.db");
statement = connection.createStatement();
} catch (Exception e){
}
try{
ResultSet resultSet = statement.executeQuery("SELECT * FROM Player_Data");
while (resultSet.next()){
MainActivity.userMoney = Double.parseDouble(resultSet.getString("userMoney"));
MainActivity.cartPrice = Double.parseDouble(resultSet.getString("cartPrice"));
MainActivity.fishStandPrice = Double.parseDouble(resultSet.getString("fishStandPrice"));
MainActivity.storePrice = Double.parseDouble(resultSet.getString("storePrice"));
MainActivity.superMarketPrice = Double.parseDouble(resultSet.getString("superMarketPrice"));
MainActivity.cartAmount = Integer.parseInt(resultSet.getString("cartAmount"));
MainActivity.fishStandAmount = Integer.parseInt(resultSet.getString("fishStandAmount"));
MainActivity.storeAmount = Integer.parseInt(resultSet.getString("storeAmount"));
MainActivity.superMarketAmount = Integer.parseInt(resultSet.getString("superMarketAmount"));
Modifiers.oysterPrice = Double.parseDouble(resultSet.getString("oysterPrice"));
Modifiers.clamPrice = Double.parseDouble(resultSet.getString("clamPrice"));
Modifiers.cocklePrice = Double.parseDouble(resultSet.getString("cocklePrice"));
Modifiers.oysterMod = Double.parseDouble(resultSet.getString("oysterMod"));
Modifiers.clamMod = Double.parseDouble(resultSet.getString("clamMod"));
Modifiers.cockleMod = Double.parseDouble(resultSet.getString("cockleMod"));
GatheringSystem.oysters = Double.parseDouble(resultSet.getString("oysters"));
GatheringSystem.clams = Double.parseDouble(resultSet.getString("clams"));
GatheringSystem.cockles = Double.parseDouble(resultSet.getString("cockles"));
}
resultSet.close();
statement.close();
connection.close();
MainActivity.databaseStarted = true;
} catch (Exception e){
MainActivity.databaseStarted = false;
}
}
}
So I am really new to coding for android and I am trying to save data for my game, so that when I come back on to the game I can read from the files.
At the moment it doesn't seem to be creating a 'database' at all.
Do I need to give it certain permissions? or can it automatically create files on a users phone?
private void databaseMethod(){
database.readFromDatabase();
if(!databaseStarted){
database.createDatabase();
toast = toast.makeText(getApplicationContext(),"Created Database",Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
distThread.setDaemon(true);
distThread.start();
databaseMethod();
File file = new File(getFilesDir(), "occDatebase.db");
}
#Override
protected void onPause() {
super.onPause();
database.writeToDatabase();
toast = toast.makeText(getApplicationContext(),"Game Saved",Toast.LENGTH_SHORT);
toast.show();
}
On creation I check to see if there is already a database, if not it should be creating one.
But it doesnt even seem to be doing that.
Any suggestions?
Thanks.
Android does not have JDBC.
And all the try/except blocks suppress any error messages.
For how to use the Android database framework, see the documentation, or any tutorial.

How to import a .xls file to mysql Database using java?

I'm trying to upload an Excel file .xls to my MySQL Database using Java NetBeans but I didn't find any solution.
I tried with CSV file and it worked fine, but I would still like to use the .xls file format.
To achieve this I want the user to click a JButton in my JFrame, choose an Excel file by using JFileChooser and then save that file in my database.
Following is the image of what I currently have:
And this is the code I used so far:
private void importer_csv_btnActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
import_interne_txt.setText(filename);
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ((line = br.readLine()) != null) {
String[] value = line.split(",");
String sql = "INSERT INTO Interne(Matricule,Nom,Prénom,Sexe,Date_naissance,Nationalité,Lieu_naissance,Willaya,Email,Moyenne1,Moyenne2,Redoublement,Conseil,Num_Phone,Password,CPI_Code) " + "VALUES('" + value[0] + "','" + value[1] + "','" + value[2] + "','" + value[3] + "','" + value[4] + "','" + value[5] + "','" + value[6] + "','" + value[7] + "','" + value[8] + "','" + value[9] + "','" + value[10] + "','" + value[11] + "','" + value[12] + "','" + value[13] + "','" + value[14] + "','" + value[15] + "')";
pst = Con.prepareStatement(sql);
pst.executeUpdate();
}
br.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Update_table();
}
Use Apache POI to read data from xls files.
Example:
public extractDataFromXls(String fileName, sheetName) throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream(fileName);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet(sheetName);
HSSFRow row = worksheet.getRow(0);
for (short i = 0; i < 5; i++) {
HSSFCell cell = row.getCell(i);
String value = cell.getStringCellValue();
System.out.println(value);
}
}

how to insert data in my sql using else if in jsp

Hi I'm trying to insert data in mysql but my page throw no response!
pease can anyone help me about it?
Code runs but println() is not displaying
//<%#page import= "java.sql.*"%>
// <%# page import="java.util.Random"%>
<%
String dt = request.getParameter("dt");
String particular = request.getParameter("vas");
String emp = request.getParameter("emp");
String amt = request.getParameter("amt");
int amnt = Integer.parseInt(amt);
//Class.forName("com.mysql.jdbc.Driver");
//Connection con = //DriverManager.getConnection("jdbc:mysql://localhost:3306/furqania", "root", "khan");
Statement st = con.createStatement();
if (particular == "amanatraseedi")
{
Random rnd = new Random();
int rn = rnd.nextInt(9000) + 10000;
String sr = "AMT" + rn;
// int i = st.executeUpdate("insert into amanatraseedi='"+particular+"'(transactionid,dt,amount,empid) values('" + sr + "','" + dt + "','" + amnt + "','" + emp + "')");
if (i > 0) {
out.println("Amanat raseedi successful!");
} else {
out.println("something went wrong!");
}
}
else if (particular == "amadhisab")
{
Random rnd = new Random();
int rn = rnd.nextInt(9000) + 10000;
String sr = "AMD" + rn;
int i = st.executeUpdate("insert into amadhisab='"+particular+"' (transactionid,dt,amount,empid) values('" + sr + "','" + dt + "','" + amnt + "','" + emp + "')");
if (i > 0) {
out.println("Amad hisab successful!");
}
else {
out.println("something went wrong!");
}
}
st.close();
con.close();
%>

Categories

Resources