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.
Related
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.
How to change the datatype from varchar to int using JDBC connection with Java of a table in MySQL?
I tried to use the query:
Alter table table_name CHANGE 'col 1' 'col 1' int (5 );
The file I am importing using the import option has the values in varchar, but I only required integer values from that table. The values of the imported table are not in ordered but the integer values are useful for me.
When I used the alter query in the phpmyadmin it works absolutely fine, but when I tried to alter in jdbc it gives me the error:
Incorrect integer value: at 'col 1';
jdbc code was as:
try {
Connection co=DriverManager.getConnection("jdbc:mysql://localhost:3306/csv_db","root",null);
String c= " ALTER TABLE tpf1 MODIFY `col 3` int(5)";
String t="Alter table table_name CHANGE 'col 1' 'col 1' int (5 );";
Statement stmt=co.createStatement();
stmt.executeUpdate(t);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, ex);
}
Edit
try {
Connection co=DriverManager.getConnection("jdbc:mysql://localhost:3306/csv_db","root",null);
String c= " ALTER TABLE tpf1 MODIFY `col ` int(20)";
Statement stmt=co.createStatement();
stmt.executeUpdate(t);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, ex);
}
The table screenshot is in the Photo:
This is actually a pdf file and converted it into .csv and imported to my database
And i only need integer values from the table not any other alphabets and symbol.
This code is only for one column and i need to alter all the three columns.So what should i do to get only integer values using jdbc? :| :)
Like #Mark Rotteveel said in comment, you have a problem in your Query so the name of your columns should be between two `` and not between two '' or "" this not work if your column name contain more then one part so to change the type of your column you should to use this :
//change column type
String query = "ALTER TABLE tablename MODIFY `col 1` INT(5)";
Statement stmt = co.createStatement();
int rslt = stmt.executeUpdate(query);
To change the name or your column use this :
//change column name
query = "ALTER TABLE tablename CHANGE `old name` `new name` INT(5);";
stmt = co.createStatement();
rslt = stmt.executeUpdate(query);
so you can check if your query executed successfully like this :
if (rslt > 0) {
System.out.println("Success");
} else {
System.out.println("Failed");
}
Note
If you change the type this will change all the column, and set it to 0
I suggest to avoid two use a name with two parts you can use col_name instead because this make a problem for example if you are using JPA.
EDIT
I try this piece of code and it work fine :
public class UpdateColumn {
static String driver = "com.mysql.jdbc.Driver";
static String DB_username = "root";
static String DB_password = "password";
static String DB_URL = "jdbc:mysql://localhost:3306/db_name";
public static void main(String args[]) {
/*read from the file*/
try {
Class.forName(driver);
java.sql.Connection co = DriverManager.getConnection(DB_URL, DB_username, DB_password);
//change column type
String query = "ALTER TABLE tablename MODIFY `c 1` INT(5);";
Statement stmt = co.createStatement();
int rslt = stmt.executeUpdate(query);
System.out.println(rslt);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
MySQL
create database db_name;
use db_name;
drop table t1;
create table tablename(
`c 1` varchar(5),
`c 2` int
);
INSERT INTO tablename values('java', 1);
INSERT INTO tablename values('mysql', 2);
Good luck.
statement.executeUpdate("ALTER TABLE table_name ALTER COLUMN column_name datatype");
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.
I am trying to figure out why ResultSet.next() is never true in Java code that I am writing after I execute a SQL query that returns results from an Oracle 11g table into that ResultSet... it seems as though the code does not pick up a returned ResultSet's contents correctly when using a PreparedStatement in a java.sql.Connection. Any help appreciated, here are the details:
Table:
CREATE TABLE "SHANDB"."ABSCLOBS"
( "ID" NUMBER,
"XMLVAL" "XMLTYPE",
"IDSTRING" VARCHAR2(20 BYTE)
)
Data:
INSERT INTO absclobs VALUES ( 1,
xmltype('<?xml version="1.0"?>
<EMP>
<EMPNO>221</EMPNO>
<ENAME>John</ENAME>
</EMP>', '1'));
INSERT INTO absclobs VALUES (2,
xmltype('<?xml version="1.0"?>
<PO>
<PONO>331</PONO>
<PONAME>PO_1</PONAME>
</PO>', '2'));
Java code I am running to get values from the above to test the code:
public static void main(String[] args) throws Exception {
try {
String url = "jdbc:oracle:thin:#//localhost:1521/xe";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "shandb";
String password = "test";
Class.forName(driver);
connection = DriverManager.getConnection(url,user, password);
String selectID1 = "SELECT a.xmlval.getClobval() AS poXML FROM absclobs a where idstring=? and id=? ";
PreparedStatement preparedStatement = connection.prepareStatement(selectID1);
preparedStatement.setString(1, "1");
preparedStatement.setInt(2, 1);
rowsUpdated = preparedStatement.executeQuery();
while(rowsUpdated.next()){
String clobxml = rowsUpdated.getString(1);
System.out.println(clobxml);
}
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
} catch (SQLException sqle) {
System.err.println(sqle);
}
finally{
System.out.println("Rows affected: " + rowsUpdated);
connection.close();
}
}
This part of the above code is never run, which I don't understand:
while(rowsUpdated.next()){
String clobxml = rowsUpdated.getString(1);
System.out.println(clobxml);
}
... however the final print statement shows that the ResultSet is not empty:
Rows affected: oracle.jdbc.driver.OracleResultSetImpl#15f157b
Does anyone know why I can't display the actual retrieved XML clob contents, and/or why the while block above is never true?
Thanks :)
Your diagnostics are incorrect - this:
Rows affected: oracle.jdbc.driver.OracleResultSetImpl#15f157b
doesn't show that the result set is non-empty. It just shows that the value of rowsUpdated is a reference to an instance of oracle.jdbc.driver.OracleResultSetImpl, which doesn't override toString(). That can very easily be empty.
I suspect the problem is just that your WHERE clause doesn't match any records. For the sake of diagnostics, I suggest you change it to just:
String selectID1 = "SELECT a.xmlval.getClobval() AS poXML FROM absclobs a";
(and get rid of the parameter-setting calls, of course). That way you should be able to see all your table's values. You can then work on discovering why your WHERE clause wasn't working as expected.
(As an aside, it's not clear why you haven't declared connection or rowsUpdated in the code in the question. They should definitely be local variables...)
I am using the following code to insert an image in a database. It will store two images because I have used PreparedStatement and Statement.
When I run this code, I get two images in the database. But the two images are different, and I don't understand why. Using PreparedStatement, it is inserting perfectly. I want to have the same image when I use Statement. Why is it not working now, and how can I make it work?
import java.io.*;
import java.sql.*;
public class Image
{
public static void main(String args[]) throws Exception
{
System.out.println("kshitij");
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jsfdb","root","kshitij");
Statement st=cn.createStatement();
File f1=new File("c:\\k1.jpg");
FileInputStream fin=new FileInputStream(f1);
//DataInputStream dataIs = new DataInputStream(new FileInputStream(f1));
PreparedStatement pst = cn.prepareStatement("insert into registration(image) values(?)");
//pst.setInt(1,67);
pst.setBinaryStream(1,fin,fin.available());
pst.executeUpdate();
//int length=(int)f1.length();
byte [] b1=new byte[(int)f1.length()];
fin.read(b1);
fin.close();
st.executeUpdate("insert into registration(image) values('"+b1+"')");
System.out.println("Quesry Executed Successfully");
FileOutputStream fout=new FileOutputStream("d://k1.jpg");
fout.write(b1);
fout.close();
}
}
MySQL
CREATE DATABASE IF NOT EXISTS jsfdb;
USE jsfdb;
-- Definition of table `registration`
DROP TABLE IF EXISTS `registration`;
CREATE TABLE `registration` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`image` blob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=234 DEFAULT CHARSET=latin1;
Of course they will be different. The following query does the following thing:
"insert into registration(image) values('"+b1+"')"
Take b1, which is a byte array, and call its toString() method. This results in a String like [B#8976876, which means "an object of type byte array with hashCode 8976876", but doesn't represent the contents of the byte array at all. Then insert this string in the table.
A byte array is not a String. End of story. You must use a prepared statement to insert binary data in a table. In fact, you should always use a prepared statement to execute any query that has a non-constant parameter.
Use setBlob with InputStream
File file= new File("your_path");
FileInputStream inputStream= new FileInputStream(file);
PreparedStatement statement = connection.prepareStatement("INSERT INTO yourTable (yourBlob) VALUES (?)");
statement.setBlob(1, inputStream);
Your problem is that you are concatenating a string with a byte array (in your call to executeStatment)
See this answer on how to insert a blob using a statement:
https://stackoverflow.com/a/2609614/355499