Inserting Data into Sql Using Java Netbeans - java

I want to insert input given by user into Sql Table using Java, but dont know how many coloumn is need.
eg.
insert into table_name values('"+id+"','"+name+"')
this query is not going to work because I don't know the column name i.e ID, name.
I want the query that is universal for any inserting data.

As per my need I tried this code. I HOPE IT WORKED FOR ALL.
void getTableInput(String tname, String dname) throws ClassNotFoundException, SQLException {
this.tname = tname;
this.dname = dname;
Scanner s = new Scanner(System.in);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String conURL = "jdbc:sqlserver://localhost:1433;databaseName=" + this.dname + ";user=JT_DATA;password=1234";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM " + this.tname);
ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
String colName[] = new String[colNo];
String[] get_User_Input = new String[100];
for (int i = 1; i <=colNo; i++)
{
colName[i-1] = rsmd.getColumnLabel(i);
System.out.print(Arrays.toString(colName) + " : ");
get_User_Input[i-1] = s.next();
}
String store="";
for(int i=0;i<colNo;i++)
{
store += "'"+get_User_Input[i]+"',";
}
store = store.substring(0,store.length() -1);
PreparedStatement pst = con.prepareStatement("insert into "+this.tname+" values ("+ store +")");
pst.executeUpdate();
System.out.println("Data Inserted");
}
But the problem with this is that. This can only insert String Datatype.

I dont think there is any universal query.
If you dont know column name than you can find name of the column by using meta data.
You can get meta data of the connections (database)
DatabaseMetaData databaseMetaData = connection.getMetaData();
You can also get list of the tables.
String catalog = null;
String schemaPattern = null;
String tableNamePattern = null;
String[] types = null;
ResultSet result = databaseMetaData.getTables(
catalog, schemaPattern, tableNamePattern, types );
while(result.next()) {
String tableName = result.getString(3);
}
Listing column name in table.
String catalog = null;
String schemaPattern = null;
String tableNamePattern = "my_table";
String columnNamePattern = null;
ResultSet result = databaseMetaData.getColumns(
catalog, schemaPattern, tableNamePattern, columnNamePattern);
while(result.next()){
String columnName = result.getString(4);
int columnType = result.getInt(5);
}
In this way you can find column name and can create query dynamically.

Related

Update data in table

The thing i want to achieve here is that i have a table name total_product in mysql database and i want to retrieve the value of SNo = 1 from the table and update the Quantity in the table.
There is a text box i am using in GUI in which the additional product produced will be written.
The output from the table is stored in variable id and the new quantity that is produced is stored in the variable q1.
so the new product quantity will be q1 = q1 + id.
I am not able to understand what should i put in the sql statement that is used in stmt.executeUpdate(sql) because the sql is a string and i have to pass an integer value to Qunty in the sql string.
Please Help.
Connection conn = null ;
Statement stmt = null ;
String url = "jdbc:mysql://localhost:3306/project";
String user = "root";
String password = ".dpadpep";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "Select Qunty from total_product " + "where SNo = 1";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int id=0;
int q1 = Integer.parseInt(fld1[0].getText());
while(rs.next()) {
id = rs.getInt(1);
System.out.println("Quantity="+id);
}
q1 = q1+id;
sql = "UPDATE total_product " + "set Qunty = q1 where SNo=1";
stmt.executeUpdate(sql);
You don't need to explicitly retrieve the current value in the database, you can simply add the additional amount directly:
int q1 = Integer.parseInt(fld1[0].getText());
String sql = "UPDATE total_product SET Qunty = Qunty + ? WHERE SNo = 1";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, q1);
ps.executeUpdate();

`createSQLException` when trying to get all rows in MySQL table

I have a simple table consisting of 4 strings and 2 integers (of which one is an ID).
I use a special function to get all rows inside that table:
public Booking[] displayAllBookings() throws ClassNotFoundException, SQLException{
Connection con = connect.getConnection();
PreparedStatement counter = (PreparedStatement) con.prepareStatement("select count(*) from bookings");
ResultSet count = counter.executeQuery();
Booking[] array = new Booking[count.getInt(1)];
String name = null,surname = null,begindate = null,enddate = null;
int persons = 0,i=0;
PreparedStatement posted = (PreparedStatement) con.prepareStatement("SELECT * FROM bookings");
result = posted.executeQuery();
while (result.next()){
begindate = result.getString("begindate");
enddate = result.getString("enddate");
name = result.getString("Name");
surname = result.getString("Surname");
persons = result.getInt("persons");
Booking temp = new Booking(begindate,enddate,name,surname,persons);
array[i++]=temp;
}
return array;
}
But when I execute it I get this exception:
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2472)
at DataBase.DataCommunicatorBooking.displayAllBookings(DataCommunicatorBooking.java:59)
at DataBase.main.displayAll(main.java:125)
at DataBase.main.main(main.java:71)
I've tried looking up this exception but I can't find anything that corresponds to my problem.
You are trying to get the value of the column maxPersons which is not even defined in the table... you meant for sure persons
name = result.getString("Name");
maxPersons = result.getInt("persons");
Room temp = new Room(name,maxPersons);
The problem was with the
PreparedStatement counter = (PreparedStatement) con.prepareStatement("select count(*) from bookings");
ResultSet count = counter.executeQuery();
so I used an ArrayList like so:
public Booking[] displayAllBookings() throws ClassNotFoundException, SQLException{
Connection con = connect.getConnection();
ArrayList<Booking> bookings = new ArrayList<Booking>();
String name = null,surname = null,begindate = null,enddate = null;
int persons = 0,i=0;
PreparedStatement posted = (PreparedStatement) con.prepareStatement("SELECT * FROM bookings");
result = posted.executeQuery();
while (result.next()){
begindate = result.getString("begindate");
enddate = result.getString("enddate");
name = result.getString("Name");
surname = result.getString("Surname");
persons = result.getInt("persons");
Booking temp = new Booking(begindate,enddate,name,surname,persons);
bookings.add(temp);
}
return bookings.toArray(new Booking[bookings.size()]);
}
and that solved the problem;
This is because the column "maxPersons" does not exist, you probably ment "persons"

Java Import Excel Data into MySQL about encoding

here my source!!
String url = "jdbc:mysql://localhost/dahan?characterEncoding=euckr";
String user = "root";
String password = "pass";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(url,user,password);
con.setAutoCommit(false);
PreparedStatement pstm = null ;
PreparedStatement pstm1 = null ;
PreparedStatement pstm2 = null ;
FileInputStream input = new FileInputStream("C:/Users/hyunwoo/Downloads/Personal Contacts.xls");
POIFSFileSystem fs = new POIFSFileSystem( input );
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Row row;
String del = "DROP TABLE IF EXISTS `dahanMail`";
String cre = "CREATE TABLE `dahanMail` (`전체이름` varchar(50),`성` varchar(50),`이름` varchar(50) ,`닉네임` varchar(50),"
+ "`회사` varchar(500),`부서` varchar(500),`직급` varchar(500),`메일주소1` varchar(50),"
+ "`메일주소2` varchar(50),`전화번호1` varchar(50),`전화번호2` varchar(50),`전화번호3` varchar(50),"
+ "`휴대폰1` varchar(50),`휴대폰2` varchar(50),`팩스1` varchar(50),`팩스2` varchar(50),"
+ "`주소` varchar(50),`웹사이트` varchar(50),`id` int NOT NULL ,PRIMARY KEY (`id`))";
pstm1 = (PreparedStatement) con.prepareStatement(del);
pstm2 = (PreparedStatement) con.prepareStatement(cre);
pstm1.execute();
pstm2.execute();
for(int i=0; i<=sheet.getLastRowNum(); i++){
row = sheet.getRow(i);
String fullname = row.getCell(0).getStringCellValue();
String lastname = row.getCell(1).getStringCellValue();
String firstname = row.getCell(2).getStringCellValue();
String nickname = row.getCell(3).getStringCellValue();
String company = row.getCell(4).getStringCellValue();
String sub = row.getCell(5).getStringCellValue();
String hei = row.getCell(6).getStringCellValue();
String mailaddress1 = row.getCell(7).getStringCellValue();
String mailaddress2 = row.getCell(8).getStringCellValue();
String cnumber1 = row.getCell(9).getStringCellValue();
String cnumber2 = row.getCell(10).getStringCellValue();
String cnumber3 = row.getCell(11).getStringCellValue();
String pnumber1 = row.getCell(12).getStringCellValue();
String pnumber2 = row.getCell(13).getStringCellValue();
String fax1 = row.getCell(14).getStringCellValue();
String fax2 = row.getCell(15).getStringCellValue();
String address = row.getCell(16).getStringCellValue();
String website = row.getCell(17).getStringCellValue();
int id = (int) row.getCell(18).getNumericCellValue();
String sql = "INSERT INTO dahanmail VALUES('"+fullname+"','"+lastname+"','"+firstname+"'"
+ ",'"+nickname+"','"+company+"','"+sub+"','"+hei+"','"+mailaddress1+"','"+mailaddress2+"','"+cnumber1+"','"+cnumber2+"','"+cnumber3+"'"
+ ",'"+pnumber1+"','"+pnumber2+"','"+fax1+"','"+fax2+"',"
+ "'"+address+"','"+website+"','"+id+"')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Import rows "+i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
I have saved the excel data to mysql using the POI in Java
and It works well!
so I checked the mysql table in cmd
but console window still show broken language like "???"
it seems to be encoding problem...
How can I change the source to fix the encoding problem?
What you have looks like it's close to working, but there are some things I would change:
Firstly, declare your SQL before the loop, with ?'s for value placeholders:
String sql = "INSERT INTO dahanmail VALUES(?,?,?)";
PreparedStatement pstm = conn.prepareStatement(sql);
(I have not put enough ?s in the code above, there should be one for each value)
Then, in the loop, you can set the parameters:
pstm.setString(1,row.getCell(0).getStringCellValue());
pstm.setString(2,row.getCell(2).getStringCellValue());
//one for each value. You could use another loop.
Then (still in the loop), execute the statement:
pstm.execute();
Finally clear the parameters for next time round:
pstm.clearParameters();

Find tables in oracle that dont have composite primary key using DatabaseMetaData Java

String [] tableTypes = { "TABLE" };
DatabaseMetaData md = (DatabaseMetaData) dbConnection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", tableTypes);
while (rs.next()) {
System.out.println(rs.getString(3));
}
Im using this part of the code to get all tables from my local oracle database but I need to change it in order to get back only the tablet that have only one primary key. Any ideas?
You could use DatabaseMetaData.getPrimaryKeys() for each table in that loop:
String [] tableTypes = { "TABLE" };
DatabaseMetaData md = dbConnection.getMetaData(); // the cast is unnecessary!
ResultSet rs = md.getTables(null, null, "%", tableTypes);
while (rs.next())
{
String schema = rs.getString(2);
String table = rs.getString(3);
ResultSet pkRs = md.getPrimaryKeys(null, schema, table);
int colCount = 0;
while (pkRs.next())
{
colCount ++;
}
pkRs.close();
if (colCount = 1)
{
System.out.println("Table " + table + " has a single column primary key");
}
}
However, this will be awfully slow. Using a query that retrieves this information directly from user_constraints and user_cons_columns is going to be a lot faster:
select col.table_name, count(*)
from user_constraints uc
join user_cons_columns col
on col.table_name = uc.table_name
and col.constraint_name = uc.constraint_name
where constraint_type = 'P'
group by col.table_name
having count(*) = 1;
You can use this code :
static Statement statement = null;
static ResultSet result = null;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
Class.forName(driverClassName);
dbConnection = DriverManager.getConnection(url, username, passwd);
statement = dbConnection.createStatement();
String[] tableTypes = {"TABLE"};
DatabaseMetaData dbmd;
dbmd = dbConnection.getMetaData();
result = dbmd.getTables("%", username, "%", new String[]{tableTypes[0]});
while (result.next()) {
String tableName = result.getString("TABLE_NAME");
ResultSet tempSet = dbmd.getPrimaryKeys(null, username, tableName);
String keyName="";
int counter=0;
while (tempSet.next()) {
keyName = tempSet.getString("COLUMN_NAME");
counter++;
}
if(counter == 1) {
System.out.println(tableName);
}
}
} catch (Exception e) {
}
}
Table can have up to one primary key. This primary can be compound - i.e. consisting of multiple columns. The other (2nd) key might be UNIQUE (+ not NULL) which is not exactly the same as primary.
Best way how to check columns is to query ALL_CONTRAINTS view. JDBC method DatabaseMetaData has only limited functionality.

How to get a particular column's values alone?

I am using the mysql java connector. I need java to display the contents of the first column and the second column in different steps. How do I achieve this?
String qry = "select col1,col2 from table1";
Resultset rs = statement.executeQuery(qry);
I've posted a sample below:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
(From: http://www.kitebird.com/articles/jdbc.html#TOC_5 )
Edit: just re-read the question and think you might mean you want to refer to a column later on in code, instead of in the inital loop as in my example above. In that case, you can create an array and refer to the array later on, or, as another answer suggests you can just do another query.
Load them into any data structure of your choice and then display them to your heart's content.
List<String> firstCol = new ArrayList<String>();
List<String> secondCol = new ArrayList<String>();
while(rs.next()){
firstCol.add(rs.getString("col1"));
secondCol.add(rs.getString("col2"));
}
Then you can manipulate with the two list as you want.
How about ... (insert drumroll here):
String qry1 = "select col1 from table1";
Resultset rs1 = statement.executeQuery(qry);
String qry2 = "select col2 from table1";
Resultset rs2 = statement.executeQuery(qry);
(You might want to phrase your question more clearly.)
You can do it like this :
String sql = "select col1,col2 from table1";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) System.out.println(rs.getString("col1"));
I am using following Code:
Statement sta;
ResultSet rs;
try {
sta = con.createStatement();
rs = sta.executeQuery("SELECT * FROM TABLENAME");
while(rs.next())
{
Id = rs.getString("COLUMN_Name1");
Vid = rs.getString("COLUMN_Name2");
System.out.println("\n ID : " + Id);
System.out.println("\n VehicleID: " + Vid);
}
}
catch(Execption e)
{
}
And this code is 100% working.
String emailid=request.getParameter("email");
System.out.println(emailid);
rt=st.executeQuery("SELECT imgname FROM selection WHERE email='emailid'");
System.out.println(rt.getString("imgname"));
while(rt.next())
{
System.out.println(rt.getString("imgname"));
finalimage=rt.getString("imgname");
}

Categories