mySQL showing null in images field - java

when I try to insert an image in MySQL database it shows:
Query OK, 1 row affected (0.06 sec)
but when I try to view it in net beans it tells that the field is null.
Also in MySQL when I put the query to display the field it shows null under the image column.
The strangest thing is that it happens only for some images and other images get added to the database and are displayed by the java net beans.
The table creation query is:
create table rto(sno int(2), image longblob);
the query to insert image in table is:
insert into rto values(2, LOAD_FILE('I:\WP_20150925_004.jpg'));
The java code is:
JFileChooser chooser=new JFileChooser();
chooser.showOpenDialog(null);
File f=chooser.getSelectedFile();
String filename=f.getAbsolutePath();
System.out.println(filename);
{
try{ int r= Integer.parseInt(jt2.getText());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/darshanproject","root","");
Statement st = con.createStatement();
String q = "Insert into rto values("+r+",LOAD_FILE('"+filename+"'));" ;
int rs = st.executeUpdate(q);
if (rs>0)
System.out.println("image inserted");
else
System.out.println("not inserted");
}catch(Exception ex){
System.out.println(ex);
}
}
// TODO add your handling code here:
}
Please help me out.

Related

Java Application script to display the number of rows in a column, of a SQL table. Error in SQL query. The output should be in a label

Hello there. I am trying to get the result of my SQL query into a label on my java application. Any advice on what I am doing wrong? (The label is "lblTest", the table is "transactions" and the column in "TRANS_ID"). Thank you in advance.
try
{
conMySQLConnectionString =
DriverManager.getConnection
(strDBConnectionString,strDBUser,strDBPassword);
stStatement = conMySQLConnectionString.createStatement();
String strQuery = "SELECT COUNT(TRANS_ID)"+"FROM transactions";
stStatement.execute(strQuery);
rs = stStatement.getResultSet();
lblTest.setText(rs.getString(1));
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
You have to check if the resultSet contains at least one record :
if(rs.first()){
lblTest.setText(rs.getString(1));
}

SQL Update statement to update document file and photo - varbinary (max)

I wrote a SQL UPDATE statement to update document file and photo stores as varbinary(max) in the DB. At first I got an error saying
Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query
So I changed the code and did it like this.
try {
//SET Varbinary_Col = CAST(Varbinary_Content as VARBINARY)
query = "UPDATE tourClient SET DocumentFile= CONVERT(varbinary(max),'"+docFile+"'),Photo= CONVERT(varbinary(max),'"+person_image+"') WHERE Name= '" + combo_client.getSelectedItem() + "' ";
PreparedStatement stm = db.getconn().prepareStatement(query);
int val = stm.executeUpdate();
if (val > 0) {
JOptionPane.showMessageDialog(null, "Uploaded successfully!!!");
rs.next();
}
db.getconn().close();
} catch (Exception e) {
System.out.println(e);
}
After I run the above query in netbeans, i get the Joption message saying uploaded successfully. I have another jframe in netbeans, which has a query that SELECTS all document files, Images and shows it in a jtable. When I click a row in jtable the image is shown in a label and the document is opened but when I try to open it, it says the file is corrupted and for the image it doesnt show the png that I uploaded.
Have I written the statement correctly? Anything I have to change?

Jtable selected row in netbeans that is bounded to sql server

I fill a jtable(tbl_student) in netbeans by this code:
String[][] result;
result = stu.Search(txt_search.getText());
String hdr[] = {"code", "name", "family"};
tbl_student = new JTable(result, hdr);
jScrollPane1.setViewportView(tbl_student);
tbl_student.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
That Search() function is a select all query from a table in sql server database.
Now, I want to find selected row in this table. How can I do it?
My code in mouse click event of this jtable is not work!
What can I do?
If you need to get some data when you clicked a row in a JTable use the following code.
int row=tbl_student.getSelectedRow();
String Table_data=(tbl_student.getModel().getValueAt(row, 0).toString()); // In here 0 means the column number.
//If you have a JTable with 5 columns; 0 is the 1st column and 4 is the last (5th) column.
If you want to get data in a database table to a JTable, their is a library called rs2xml.jar with the help of that library you can simply fill a JTable with database data.
You can download that library from HERE.
After downloading library use the following code to fill your JTable.
Connection conn=null;
ResultSet rs=null;
PreparedStatement pst=null;
try{
String sql="SELECT * FROM table_name"
conn=java_connect.ConnecrDb(); //Database connecting class
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
tbl_student.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}

Updating existing Row on database jdbc

No error is showing when i click the button but the table on the database doesn't update.
String heh = jLabel17.getText();
try {
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch (SQLException err) {
System.out.println(err.getMessage() );
}
You have messed up the query totally,
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
should be,
stmt.executeUpdate("UPDATE books SET availability='Unavailable' where Book_title='"+heh+"' ");
It is advisable to print query before you execute , as that avoids common mistakes. Also try to use Prepared Statements as yours is vulnerable to sql injection
Read this Prepared Statements and JDBC Drivers
AFTER HOURS OF RESEARCH, I FOUND THE SOLUTION, I REPLACED THIS
String heh = jLabel17.getText();
try{
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch(SQLException err){
System.out.println(err);
}
WITH THIS CODE
String heh = jLabel17.getText();
try{
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Dafuq7","Dafuq7","Dafuq7");
// Creating Statement for query execution
stmt = con.createStatement();
// creating Query String
String query = "UPDATE books SET availability='NOT AVAILABLE' WHERE book_title='"+heh+"'";
// Updating Table
int rows = stmt.executeUpdate(query);
System.out.println(rows + " Rows Updated Successfully....");
} catch (Exception e) {
System.out.println(e.toString());
}

how to insert image in to database

CREATE TABLE IMGTABLE
(
NAME char,
PHOTO blob
)
This is Query for imagetable:
import java.sql.*;
import java.io.*;
public class arralistclaaa
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
PreparedStatement ps = con.prepareStatement("insert into imgtable values(?,?)");
ps.setString(1, "sonoo");
FileInputStream fin = new FileInputStream("E:\\actsandrulesMobile_biggerb.png");
ps.setBinaryStream(2, fin, fin.available());
int i = ps.executeUpdate();
System.out.println(i + " records affected");
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This is Java class code for insert image in database When i run this code then com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'NAME' at row 1 this Error is coming i dont know where is Problem to insert image in data base please help me why this Error is coming.
Why did you use char instead of varchar(100) in NAME column. Change Name column type to varchar
The issue at hand is that your value for NAME is too long. Your table definition has it as a single character (Or zero characters? I honestly don't know what you get with char and no size).
Also, PreparedStatement includes a .setBlob() method that takes an InputStream as the second argument.
http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setBlob%28int,%20java.io.InputStream%29
Change ´char´ to ´varchar´ in your table like this :
CREATE TABLE IMGTABLE
( NAME varchar,
PHOTO blob
)
No need of Storing entire Image in DB, Just Store Image Path in the column (upload Image in Server) and retrieve it and form the Path and Display it in Browser.

Categories