adding new column to table with column name as present days date - java

I am new to java .I want to build simple java application for attendance management system.For doing this I want to create a new column into already existing table the column name should be present days date.I used date picker for getting present days date.
I had written following code for this,but the column name in table is setting as "+s1+".
This is my code:
String s="";
s=date.getText();//selected data from date picker
s.replace(".","_");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:vasu");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//System.out.println("ALTER TABLE attendance ADD "+s+" varchar(50);");
rs = st.executeQuery("ALTER TABLE attendance ADD '"+s+"' varchar(50);");
}
catch(Exception ex){
}
could any one help me
well thanks in advance.

Try this
executeUpdate return 1 if the query work properly otherwise it will return 0
String s="";
s=date.getText();//selected data from date picker
s.replace(".","_");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
ResultSet acrs;
String op = "jdbc:odbc:vasu";
Connection cnn = DriverManager.getConnection(op,"username", "password");
Statement mystmt = cnn.createStatement();
int successOrFailure = mystmt.executeUpdate("ALTER TABLE attendance ADD '"+s+"' VARCHAR(50)");
//executeUpdate return 1 if the query work properly otherwise it will return 0
}catch(Exception e)
{
System.out.println("Exception:"+e);
e.printStackTrace();
}

Related

sort sql results and display all the results by a loop in a table in java

I want to sort sql results with a date that i get from jDateChooser and display all the returned results. This is what i have done so far. So far I have only managed to get 1 result even if i looped the sorted sql results.
public void MonthlyTotalExpenses_Report(){
String typeOfReport = (String) report_type.getSelectedItem();
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText();
db databaseCon = new db();
Connection dbconnect = db.dbconnect();
if(typeOfReport == "Total expenses"){
String selectQuery = "select name,type,sum(amount),date_payed from expenses order by ? DESC";
try{
Connection con = databaseCon.dbconnect();
ResultSet rs = null;
PreparedStatement pst = null;
pst = con.prepareStatement(selectQuery);
pst.setString(1,reportDate);
rs = pst.executeQuery();
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
for(String result : results) {
System.out.println(result);
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I want sort the results like this (for example -> 2017-01-01 to the date user select with jDateChooser) and print all the records available within that period. I just figured the sql query i wrote is wrong. It only prints the 1st value of the name column in the database. Help me to figure out how to sort according what i have mentioned above and print all the results that returned.
You might want to set the date in the where condition in your query.
select name,type,sum(amount),date_payed from expenses where date_payed = ? order by 4 DESC
Consider obtaining Date from String.
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText(); // "2017-01-01"
DateFormat format = new SimpleDateFormat("YYYY-MM-DD", Locale.ENGLISH);
Date date = format.parse(reportDate);
Then set your param with
pst.setDate(1,reportDate);

How to update mysql database value from java netbeans

How to update mysql database value from java netbeans
I need to update one of my selected column value
this table has 6 column but I need to update one column only (6th column)
So how to do this -
I use this code -
connectDB();
try{
String value1 = txt_searchcode.getText();
String value6 = Final_stock_view.getText();
String sql = "Update tbl_codes set No='"+value1+"',Bin_Balance='"+value6+"'WHERE No='"+value1+"' ";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.execute();
JOptionPane.showMessageDialog(null, " Your new records Updated Succsessfully!!");
}catch(Exception e){
JOptionPane.showMessageDialog(null," Update Failed");
}
closeDB();
its running well without any errors, but nothing happen
So how to fix this...... (Examples)
Thanks

Fill jTextField with records when selecting from jComboBox (Java database)

How do you go about putting records into a jTextField when an item is selected from a jComboBox? For example, I'm making an airline reservation system and I have a combo box with the available flights. Below it are text fields with designated info like departure date, departure time, arrival date, etc. How do I make it so that when the user selects an item from the the combo box, (ex. flight name is CX9005) the corresponding info from the same row is shown in the text fields? (ex. departure date is November 12 2015)
EDIT:
So I tried doing that with the ff. code, but I got a syntax error and a ResultSet not open error.
private void combo_FlightItemStateChanged(java.awt.event.ItemEvent evt) {
try{
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
rs = stmt.executeQuery(query);
}
catch(SQLException err){
JOptionPane.showMessageDialog(UserModule.this, err.getMessage());
}
}
Also, I use this function to connect to my database if that matters.
public void DoConnect() {
try{
String host = "jdbc:derby://localhost:1527/UserAccounts";
String uName = "Bryan";
String uPass = "Cruz";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM ACCOUNTS";
rs = stmt.executeQuery(sql);
}catch(SQLException err){
JOptionPane.showMessageDialog(Connect.this, err.getMessage());
}
}
Also, I might not have been too clear with my original post. I want to make it so that when the user selects a flight from the combo box, all of that flight's details show up in the appropriate text fields. (ex. departure date, departure time, destination, etc.) I'm confused on how to make this work so help would be much appreciated!
You get the text from the comboBox using getSelectedItem() or getSelectedValue().
You can then create a MySQL query like:
String flightName = yourComboBox.getSelectedItem().toString();
String query= "Select * from yourTable where flightName = \'"+flightName+"\';";
Then you can execute this query using executeQuery()
Now for the part with setting results in all testfields
First store the result in a ResultSet object
rs = stmt.executeQuery(query);
rs.next();
Now you have the result in object rs
Use rs.getString(columnNumber) to get records from the result
Eg.
String departureDate = rs.getString(4);
// assuming the column number is 4
Do this to get all required strings.
And set them in respected columns using setText() method
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
What is the point of the above two statements? You can't get two values from the same combo box. Either you get the flightID or the flighName.
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
but I got a syntax error
Don't try to build the SQL string manually. Instead you can use a PreparedStatement. It will make sure the proper delimiters are used so you just concentrate on the SQL statement:
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString( 1, flightName );
ResultSet rs = stmt.executeQuery();
So you will need access to the Connection object you established in the doConnect() method. Note, method names should NOT start with an upper case character.
Also, I believe the standard for database column names is to capitalize the words of the column, so you should be using "FlightName" not "flightName" as the column name.

"all columns must be set before insert" error on a ResultSet insert with UCanAccess

I want to create an Access database connection using UCanAccess under Java 8. Here is my code:
String employeeName = endrollNameFields.getText();
String employeeAddress = endrollAddressFields.getText();
try
{
//------------CREATE CONNECTION TO DATA BASE--------------/
String DBPAD = "sourceFolder\\employeeTable2.mdb";
String DB = "jdbc:ucanaccess://" + DBPAD;
con = DriverManager.getConnection(DB, "", "");
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "select * from employeeTable2";
rs = st.executeQuery(sql);
rs.moveToInsertRow();
rs.updateString("Name", employeeName);
rs.updateString("Address", employeeAddress);
rs.insertRow();
st.close();
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql1 = "select * from employeeTable2";
rs = st.executeQuery(sql1);
JOptionPane.showMessageDialog(null, "<html>" + "<font color=\"#008000\">" + "<html><span style='font-size:1.5em'>Employee Successfuly Inserted to Data Base");
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, e1);
}
I made entries to my JTextField but when i click the button containing codes above this error message appears:
net.ucanaccess.jdbc.Ucanaccess SQLException:invalid cursor state: all columns must be set before insert
What is missing or lacking in my code?
UCanAccess uses HSQLDB as a "backing database", and HSQLDB requires that all columns in the insert row be given an explicit value before calling .insertRow(), including using rs.updateNull("ColumnName") to explicitly specify a NULL value. That's just the way it works.
This was discussed recently on SourceForge here. The requirement may be lifted in a future version of UCanAccess.
UPDATE
UCanAccess version 3.x, released in August 2015, has indeed removed the above requirement. Any columns not explicitly set in the insert row will contain the default value for the column (or NULL if the column is nullable and no default value is specified in the table definition).

Java Database adding to row I deleted?

Ok So I have a program where I add new Players to a database, and where I load them users into a list. The problem is when I delete a user, then go to add a new user the new player gets added in to where the old user was. Basically because that spot is free now and I use:
rs.moveToInsertRow();
is there a way that when adding a new player it 'Always' adds to the end of the the database. Like when you delete a row from table to make the database compress so it has no gaps?
here is the code:
public static void Save() { try {
String Name = "#####";
String Pass= "#####";
String Host = "######";
Connection con = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "####", "####"),
Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM Accounts";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
String userName= TestForm.UsernameTextField.getText(); //make this equal to whats in textfield
String password= TestForm.PasswordTextField.getText(); //make this equal to whats in textfield
String insertQuery="insert into Accounts (`Username`,`Password`) values ('"+userName+"','"+password+"');";
stmt.executeUpdate(insertQuery);
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
What's your table create statement? SHOW CREATE TABLE Accounts ;
Seems like an AUTO_INCREMENT integer primary key in the table would help your issue.

Categories

Resources