I have to write Junit for below method. How i can cover catch block with Junit
using #Test(expected = SQLException.class).
public int getId(final String col1, final int col2,
String col3) throws DatabaseDownException {
final String IdQuery = "Select id from Manager where col1= ? and col2 = ? and col3 = ?";
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int Id = 0;
try {
con = getDataSource().getConnection();
stmt = con.prepareStatement(IdQuery);
stmt.setString(1, col1);
stmt.setInt(2, col2);
stmt.setString(3, col3);
rs = stmt.executeQuery();
if (null != rs && rs.next()) {
Id = rs.getInt(1);
}
} catch (SQLException e) {
logger.error("ERROR-WARNING:<<<getId():: ID "+col1+" SQLException occurred while selecting data table.");
} finally {
cleanUp(rs, stmt, con);
}
return Id;
}
You should create an inner method from the code inside try block (refactor extract method) that both JUnit test and your method will use:
protected int getId(final String col1, final int col2, String col3, final String IdQuery, int Id) throws SQLException {
Connection con;
PreparedStatement stmt;
ResultSet rs;
con = getDataSource().getConnection();
stmt = con.prepareStatement(IdQuery);
stmt.setString(1, col1);
stmt.setInt(2, col2);
stmt.setString(3, col3);
rs = stmt.executeQuery();
if (null != rs && rs.next()) {
Id = rs.getInt(1);
}
return Id;
}
Unit test:
#Test(expected = SQLException.class)
public void testGetId() {
getId(...)
}
Related
I am trying to make a java program can call a table by its name... but the problem is I couldnt figure out how to check if the table is exist or not in database... I am using phpmyadmin data base and here is my code if there is someone can help me ...
enter image description here
public boolean istableNameexist(String un){
boolean uexist = false;
Connection con = myConnection.getconnection();
PreparedStatement ps;
ResultSet rs;
try {
ps = con.prepareStatement("SELECT * FROM `javacontactapp` WHERE TABLE_NAME = ?");
ps.setString(1,name.getText());
rs = ps.executeQuery();
if (rs.next()){
uexist = true;
}
} catch (Exception e) {
System.out.println("wrong");
}
return uexist;
}
public void openfatura(ActionEvent actionEvent) {
String ff1 = name.getText();
Connection con = myConnection.getconnection();
if (!name.getText().isEmpty()) {
if (istableNameexist(name.getText())){
try {
PreparedStatement ps = con.prepareStatement("SELECT `dafat`, `sinif` ,`number` , `price`, `type`, `total` FROM " + ff1 + " WHERE `id` = 1");
ResultSet resultset = ps.executeQuery();
I am running a query on ID column but I don't want it to be visible in my frame/pane. How can I achieve this? Shall I make another table, is there a function in sql/mysql which allows to hide columns? I tried to google it but havent found anything yet.
Here is the code:
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
Connection connection = TableWithBottomLine.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
+ " where ID = " + studId + ";");
stmt.executeBatch();
connection.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
connection.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
int rowCount;
Object data [][];
String columnNames [];
public MyTableModel() throws SQLException{
String query ="SELECT ID, tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport, Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
ResultSet rs ;
Connection connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][11];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getInt("ID");
data[iEil][1] = rs.getDate("Date");
data[iEil][2] = rs.getFloat("Flat");
data[iEil][3] = rs.getFloat("Mobile");
data[iEil][4] = rs.getFloat("Food");
data[iEil][5] = rs.getFloat("Alcohol");
data[iEil][6] = rs.getFloat("Transport");
data[iEil][7] = rs.getFloat("Outdoor");
data[iEil][8] = rs.getFloat("Pauls_stuff");
data[iEil][9] = rs.getFloat("Income");
data[iEil][10] = rs.getFloat("Stuff");
}
String[] columnName = {"ID", "Date","Flat","Mobile"
,"Food","Alcohol","Transport", "Outdoor", "Pauls_stuff", "Income", "Stuff"};
columnNames = columnName;
}
This has solved my problem:
table.removeColumn(table.getColumnModel().getColumn(0));
I placed this in my class contructor. This lets remove the column from the view of the table but column 'ID' is still contained in the TableModel. I found that many people looking for an option to exclude specific column (like autoincrement) from SELECT statement in sql / mysql but the language itself doesn't have that feature. So I hope this solution will help others as well.
Don't put ID in the select part of the query
String query ="SELECT tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport,
Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
I am looking at a code written way back in time. It looks like this
public String MaxID() throws SQLException {
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
conn = DriverManager.getConnection(get_db_url(), get_db_id(), get_db_pw());
stmt = conn.createStatement();
String sql = null;
sql = "select MAX(id)+1 AS count from tbl1";
rset = stmt.executeQuery (sql);
rset.next();
String newId = rset.getString("count");
if (newId == null)
newId = "1";
return newId;
} catch (SQLException e) {
return ("<P> SQL error: <PRE> " + e + " </PRE> </P>\n");
} finally {
if (rset!= null) rset.close();
if (stmt!= null) stmt.close();
if (conn!= null) conn.close();
}
}
When I try to run it I receive the following output:
An error occurred at line: 146 in the jsp file: /functions.jsp
Unhandled exception type SQLException
143: ResultSet rset = null;
144:
145:
146: DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
147: conn = DriverManager.getConnection(get_db_url(), get_db_id(), get_db_pw());
148: stmt = conn.createStatement();
149: String sql = null;
And I can not understand why. It sems to be handled in a proper way (according to what I have read in the docs)
I don't know why but the table doesnot display. Values are being added into base table in mysql but it doesnot display in jtable.
Connection con = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = con.createStatement();
String sql = "insert into customers "+
"values("+id+", \""+name+"\", "+"\""+add+"\", "+pno+");";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery("Select * from customers;");
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
model.addColumn("CustID");
model.addColumn("CustName");
model.addColumn("CustAdd");
model.addColumn("PhoneNo");
while(rs.next()){
int tid = rs.getInt("custid");
String tname = rs.getString("custname");
String tadd = rs.getString("custadd");
long tpno = rs.getLong("phoneno");
model.addRow(new Object[]{tid, tname, tadd, tpno});
}
table.setVisible(true);
}catch(SQLException se){
jOptionPane1.showMessageDialog(this, se);
}catch(Exception e){
.
.
.
You add the JTable to the JScrollPane, but it does not look like you are adding the JScrollPane to anything. (Unless there is code that we are not seeing.)
I have a mySQL table named userinfo with colums- userId, userName, Password, city, age- userId is Pkey and Autoincremnt
When a user Login on a login.jsp, he submits username and Pasword.
These two parameters of login.jsp are received in UserLogin servlet and then checked in userinfo Table. If matched, he could log in.
I tried SELECT but I get numerous error. What should be the correct way:-
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt = (PreparedStatement) conn
.prepareStatement(sql);
ptmt.executeQuery();
Statement stmt = (Statement) conn.createStatement();
s = connection.prepareStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo = ?");
//storing user data in ResultSet
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String refName = rs.getString("UserName");
String refPass = rs.getString("UserPW");
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
by using Statement interface you can not dynamically set the values. use PreparedStatement interface for second query.
import package in you class import javas.sql.*;
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser UserName = ?";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt =conn.prepareStatement(sql);
ptmt.setString(1, user)
ResultSet rs= ptmt.executeQuery();
while (rs.next()) {
String refName = rs.getString(1);//field index of user name
String refPass = rs.getString(2);//field index of password
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
Are you asking for the entire code listing? in your current code you seem to be executing some queries for no reason, then getting a list of all users and iterating through them looking for a match. Try using a query like
sql ="Select UserName, UserPW From SocialNetwork.RegisteredUser where UserName=?"
ResultSet rs = stmt.executeQuery(sql);
then check the password in code
if(rs.next()){
String refPass = rs.getString("UserPW");
if (pw.equals(refPass) )
}