I want to insert values into a database table. The table has two columns: id and image. The id is an auto-increment int and the image is a blob type. Here is my code:
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, userName, password);
File imgfile = new File(request.getParameter("img"));
InputStream fin = new FileInputStream(imgfile);
PreparedStatement pre = con.prepareStatement("insert into pictures (image) values(?)");
pre.setBinaryStream(1, fin, imgfile.length());
int done=pre.executeUpdate();
} catch(SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
I check the database and nothing inserted. Server Output:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for
column 'image' at row 1
I fixed it. I changed the data type of the image column from blob to longblob Thanks.
Related
I'm creating a desktop App where user can import file and retrieve them from database (SQlite) and them see or modify data
So if someone can help me with all this
1.I created database using SQLITE
2.I used button for filechooser then A button save for import to database
Problems
1. Open file (done)
2.saving into database (No)
U can see my code
Mycode open button
public void openfolder (ActionEvent event) throws IOException {
FileChooser fc = new FileChooser();
fc.setInitialDirectory(new File("C:\\Users\\Lenovo\\Documents\\NetBeansProjects\\sogece\\src\\PDFimport"));
fc.getExtensionFilters().addAll(
new ExtensionFilter("PDF Files","*.PDF"));
List<File> selectedFiles = fc.showOpenMultipleDialog(null);
if (selectedFiles !=null){
for(int i =0;i <selectedFiles.size();i++){
listview.getItems().add(selectedFiles.get(i) .getAbsolutePath());
}}else{
System.out.println("file is not valid");
}}
Mycode save button
String query = "INSERT INTO PDFS (liste) VALUES (" + listview.getAccessibleText()
+ ")";
System.out.println("Inserting\n" + query);
insertStatement(query);
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sogeclair.sqlite");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
stmt.close();
c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getField(query) + ": " + e.getMessage());
System.exit(0);
}
and the error
Inserting
INSERT INTO PDFS (liste) VALUES (null)
Opened database successfully
Our query was: INSERT INTO PDFS (liste) VALUES (null)
Opened database successfully
Deleting directory
C:\Users\Lenovo\Documents\NetBeansProjects\sogece\dist\run674970846
Then I used another solution for Import PDF but I got this as ERROR
Code
String query = "INSERT INTO PDFS (liste) VALUES (?) "try (PreparedStatement stm = connection.prepareStatement(query) {
//NOTE: Position indexes start at 1, not 0
stm.setString(1, listview.getAccessibleText ());
stm.executeUpdate();
}
error
java.lang.UnsupportedOperationException: Not supported yet. at sogeclair.connection.prepareStatement(connection.java:17) at sogeclair.PlanningController.btninsert(PlanningController.java:285) ... 58.
I went Back to verify the problem but I didn't understand what does it mean
Connection.java :17
class connection { static PreparedStatement prepareStatement(String query) { throw new UnsupportedOperationException("Not supported yet.");
PlanningController.java:285 :try (PreparedStatement stm = connection.prepareStatement(query))
Change this:
String query = "INSERT INTO PDFS (liste) VALUES (" +listview.getAccessibleText ()+ ")";
To this :
String query = "INSERT INTO PDFS (liste) VALUES ('" +listview.getAccessibleText ()+ "')";
VARCHAR type should between two ''
Note
This can cause a syntax error or SQL Injection instead you have to use PreparedStatement
String query = "INSERT INTO PDFS (liste) VALUES (?)";
try (PreparedStatement stm = connection.prepareStatement(query) {
//NOTE: Position indexes start at 1, not 0
stm.setString(1, listview.getAccessibleText ());
stm.executeUpdate();
}
I have a registration page where information for a customer can be entered into 4 text fields, i.e. Customer name, customer address, customer email and customer contact number.
I was wondering how to get the data from the text fields and into the Derby Database in netbeans using Java.
Well, you need to get the text from the fields first, so as follows:
//Replace the textfield names with your textfield variable names
String customerName = txtFieldCustomerName.getText();
String customerAddress = txtFieldCustomerAddress.getText();
String customerEmail = txtFieldCustomerEmail.getText();
String customerContactNumber = txtFieldCustomerContactNumber.getText();
Now that we have all the data, we can perform a database insert
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
con = DriverManager.getConnection("jdbc:derby://localhost:1527/myDB;create=true;user=me;password=mine");//Replace this with your information to your database
//now we have a connection, we can perform the insert
pstmt = con.prepareStatement("insert into TABLE_NAME_HERE (customerName, customerAddress, customerEmail, customerContactNumber) VALUES (?, ?, ?, ?)");
pstmt.prepareString(1, customerName);
pstmt.prepareString(2, customerAddress);
pstmt.prepareString(3, customerEmail);
pstmt.prepareString(4, customerContactNumber);
pstmt.executeUpdate(); //execute the insert
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally { //close the connection after everything is done.
try {
con.close();
pstmt.close();
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}
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.
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.
tb_records = jtable name
records = table name inside my database
Date = my first column
hey = substitute for my real password
mydatabase = name of my database
My problem is that, when I highlight a row in my JTable and delete it, it deletes all the rows. I want to delete the selected row only. Here's my code:
int row = tb_records.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tb_records.getModel();
String selected = model.getValueAt(row, 0).toString();
if (row >= 0) {
model.removeRow(row);
try {
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "hey");
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
ps.executeUpdate();
}
catch (Exception w) {
JOptionPane.showMessageDialog(this, "Connection Error!");
}
}
What could be the problem here? How can I delete a selected row in my database and not all the rows?
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
int row = jTable.getSelectedRow();
String eve = jTable.getModel().getValueAt(row, 0).
String delRow = "delete from user where id="+eve;
try {
ps = myCon.getConnection().prepareStatement(delRow);
ps.execute();
JOptionPane.showMessageDialog(null, "Congratulation !!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
1) Don't display your own message. Display the error message from the Exception as it will give a better explanation what the problem is.
2) Use a proper PreparedStatement for the SQL. You are less likely to make syntax errors. Something like:
String sql = "delete from records where Date= ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, selected );
stmt.executeUpdate();
I don't know much about SQL but maybe you need to pass a Date object not a String object since your where clause is using a Date?
The OP wrote:
SOLUTION: Pick a column with unique values. My Date column has the same values that's why it's deleting all my rows even though I set my row as getSelectedRow. Time_in = my 4th column with unique values.
change
String selected = model.getValueAt(row, 0).toString();
to
String selected = model.getValueAt(row, 3).toString();
and
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
to
PreparedStatement ps = conn.prepareStatement("delete from records where Time_in='"+selected+"' ");