I am very much new at SQL. Hopefully someone will be able to help with this problem. I need to create an query that will automate the updates of one of my column. How do I go about writing that?Any help would be much appreciated it
Please do following actions, (JAVA)
Add DB driver dependency to your program
Construct your query
Pass it your DB driver
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://"+url+"/VSS-AlertManager?user="+username+"&password="+password);
st = con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ResultSetMetaData md = rs.getMetaData();
int colCount = md.getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 1; i <= colCount ; i++){
String col_name = md.getColumnName(i);
String col_value = rs.getString(col_name);
System.out.println(col_name + col_value );
}
}
} catch (SQLException | ClassNotFoundException throwables) {
throwables.printStackTrace();
log.error("Error occurred in executing mysql : "+throwables.toString());
}
Related
I am writing methods through JDBC to create a table and a sequence to recall in a Trigger, I want to set up an id column which auto-increments before every insert on the table. I succeeded in building both the createTable method and the createSequence method in the DAO, but when I run the method to create the Trigger I got the java.sql.SQLException: Missing IN or OUT parameter at index:: 1
public void createTrigger() {
PreparedStatement ps;
StringBuilder queryTrigger = new StringBuilder();
queryTrigger.append("CREATE OR REPLACE TRIGGER ");
queryTrigger.append(Tables.getInstance().getName() + "_INSERTED\n");
queryTrigger.append("BEFORE INSERT ON " + Tabelle.getInstance().getName());
queryTrigger.append("\nFOR EACH ROW\n");
queryTrigger.append("BEGIN\n");
queryTrigger.append("SELECT " + Tables.getInstance().getName() + "SEQ.NEXTVAL\n");
queryTrigger.append("INTO :new.id\n");
queryTrigger.append("FROM dual;\n ");
queryTrigger.append("END;\n");
queryTrigger.append("/\n");
queryTrigger.append("ALTER TRIGGER " +Tabelle.getInstance().getName() + "_INSERTED ENABLE\n");
queryTrigger.append("/\n");
String stringQueryTrigger = queryTrigger.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(stringQueryTrigger);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);}
Here instead the creation of the table does actually work even if I don't
write the classic lines with parametrized "?" for the preparedStatement.setString(index, String)
public void createTable(Columns c) {
PreparedStatement ps;
StringBuilder query = new StringBuilder();
query.append("CREATE TABLE " + Tabelle.getInstance().getName() + "(");
query.append(Columns.getInstance().getColumnName() + " ");
query.append(Columns.getInstance().getDataType());
if(Columns.getInstance().isNullOrNot() == true) {
query.append(" NOT NULL");
}
else {
query.append("");
}
if(Columns.getInstance().isPrimaryKeyOrNot() == true) {
query.append(" PRIMARY KEY)");
}
else {
query.append(")");
}
String queryToString = query.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(queryToString);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);
}
//EDIT
turns out that is enough to substitute the PreparedStatement with a simple Statement, to get rid of the indexes mechanism and get the DB to accept the query
I would suggest creating an auto-increment sequnce in oracle that can be used for all ids and just add the string id.NextVal to the string query
What I mean is:
Rem in oracle create sequence
CREATE SEQUENCE ID
START BY 1
INCREMENT 1
// in java to execute query
String query = "INSERT INTO TABLE VALUES(ID.NEXTVAL);" ;
//rest of code
I had the error in this code snippet:
private String[][] connectToDB(String query) throws ClassNotFoundException{
String[][] results = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=E:/EACA_AgroVentures1.accdb";
conn = DriverManager.getConnection(db);
stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsm = rs.getMetaData();
rs.beforeFirst();
int columns = rsm.getColumnCount();
int rows = getRowCount(rs);
//int rows = rs.getFetchSize();
int rowCount = 0;
results = new String[rows][columns];
//System.out.println(rows+" "+columns);
while((rs!=null) && (rs.next())){
for(int i = 1; i < columns; i++){
results[rowCount][i-1] = rs.getString(i); // --> ERROR SHOWS HERE
//System.out.println(rowCount+","+i+" = "+rs.getString(i));
}
rowCount++;
}
rs.getStatement().close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
return results;
}
My query consists of the following:
private void loadMR(){
try {
String query = "SELECT dealerCode, SUM(kg) AS totalKG, SUM(price) AS totalPrice, returnDate, BID FROM meatReturns GROUP BY BID, dealerCode, returnDate;";
Object[][] result = connectToDB(query);
// some more code below..
I tried using the first code with some other query given in another method:
private void loadDealers(){
try {
String query = "SELECT * FROM Dealers";
Object[][] result = connectToDBWithRows(
query);
// some more code..
and it runs perfectly well. What is going on here? How can i fix this problem?
UPDATE: the only difference of connectToDBWithRows and connectToDB is the while loop that manages the resultSet
// Snippet from connectToDBWithRows()
while((rs!=null) && (rs.next())){
for(int i = 0; i < columns; i++){
if (i == 0){
// Do nothing
}else{
results[rowCount][i] = rs.getString(i);
//System.out.println(rowCount+","+i+" = "+rs.getString(i));
}
}
rowCount++;
}
and this is my getRowCount() method
private int getRowCount(ResultSet resultSet){
int size = 0;
try {
resultSet.last();
size = resultSet.getRow();
resultSet.beforeFirst();
}
catch(Exception ex) {
return 0;
}
return size;
}
I've noticed that sometimes, Access needs you to specify the table name when referring to columns in sql statements. Try the following:
private void loadMR(){
try {
String query = "SELECT meatReturns.dealerCode, SUM(meatReturns.kg) AS totalKG, SUM(meatReturns.price) AS totalPrice, meatReturns.returnDate, meatReturns.BID FROM meatReturns GROUP BY meatReturns.BID, meatReturns.dealerCode, meatReturns.returnDate";
Object[][] result = connectToDBWithRows(query);
I try to code a forum using java swing. Firstly, on click for the jTable, it will lead to eForumContent.class which pass in the id together.
jTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
int id = 0;
eForumTopics topics = new eForumTopics(id);
topics.retrieveDiscussion();
eForumThreadContent myWindow = new eForumThreadContent(id);
myWindow.getJFrame().setVisible(true);
}
});
I initialize the id first. But I set my id in database table to auto number. Then I call the retrieveDiscussion method to get the id from database and pass it to eForumThreadContent. Here are my codes for retrieveDiscussion method.
public boolean retrieveDiscussion(){
boolean success = false;
ResultSet rs = null;
DBController db = new DBController();
db.setUp("IT Innovation Project");
String dbQuery = "SELECT * FROM forumTopics WHERE topic_id = '" + id
+ "'";
rs = db.readRequest(dbQuery);
db.terminate();
return success;
}
}
Then, inside the eForumThreadContent, I want to display the content of chosen thread using a table. So I use the id which I pass in just now and insert into my sql statement. Here are my codes.
public eForumThreadContent(int id) {
this.id = id;
}
if (jTable == null) {
Vector columnNames = new Vector(); // Vector class allows dynamic
// array of objects
Vector data = new Vector();
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select topic_title,topic_description,topic_by from forumTopics WHERE topic_id = '"+id+"'";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
if (i == 1) {
column.setPreferredWidth(400); // second column is bigger
}else {
column.setPreferredWidth(200);
}
}
String header[] = { "Title", "Description", "Posted by" };
for (int i = 0; i < jTable.getColumnCount(); i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel()
.getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.getTableHeader().setFont( new Font( "Dialog" , Font.PLAIN, 20 ));
jTable.getTableHeader().setForeground(Color.white);
jTable.getTableHeader().setBackground(new Color(102, 102, 102));
jTable.setEnabled(false);
jTable.setRowHeight(100);
jTable.getRowHeight();
jTable.setFont( new Font( "Dialog" , Font.PLAIN, 18 ));
}
return jTable;
}
However, the table inside eForumThreadContent is empty even when I clicked on certain thread. It also gives me an error message.
[Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
at DBController.database.DBController.readRequest(DBController.java:27)
at kioskeForum.entity.eForumTopics.retrieveDiscussion(eForumTopics.java:67)
at kioskeForum.ui.eForumDiscussion$3.mouseClicked(eForumDiscussion.java:296)
I research online to get an idea for topic views using id. But my table does not show up anything. Can somebody enlighten me how to fix it? Or any other ways to display topic views in java swing? Thanks in advance.
I can't get what is happening to my app. I'm using a SQL CE (.sdf file) to a local database (winform app) and when I debug, everything runs pretty well, I have in the end of it the message that my data was inserted well. But later on, when I check my databse, its empty.
What should I do?
This is my code:
SqlCeConnection conn = new SqlCeConnection(#"Data Source=|DataDirectory|\Database\Livraria.sdf;");
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO Livros (Codigo, ISBN, Titulo, Editora, Localizacao, Valor, QTD, Autor, AutorEspiritual, Data_)
VALUES (#Codigo, #ISBN, #Titulo, #Editora, #Localizacao, #Valor, #QTD, #Autor, #AutorEspiritual, #Data_)";
cmd.Parameters.AddWithValue("#Codigo", codigo);
cmd.Parameters.AddWithValue("#ISBN", isbn);
cmd.Parameters.AddWithValue("#Titulo", titulo);
cmd.Parameters.AddWithValue("#Editora", editora);
cmd.Parameters.AddWithValue("#Localizacao", localizacao);
cmd.Parameters.AddWithValue("#Valor", valor);
cmd.Parameters.AddWithValue("#QTD", entradas);
cmd.Parameters.AddWithValue("#Autor", autor);
cmd.Parameters.AddWithValue("#AutorEspiritual", autorEspiritual);
cmd.Parameters.AddWithValue("#Data_", data_);
try
{
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Livro adicionado com sucesso!");
}
else
{
MessageBox.Show("O livro não foi adicionado.");
}
// Reset campos
Codigo.Text = "";
Titulo.Text = "";
Editora.SelectedIndex = 0;
Valor.SelectedIndex = 0;
Localizacao.SelectedIndex = 0;
Entrada.Text = "";
Isbn.Text = "";
Autor.SelectedIndex = 0;
AutorEspiritual.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
You have two databases. You are inserting to one and looking for the results in another.
Or, you are starting a transaction, inserting but then not committing.
The first thing you need to do is to create a simple select statement first that gets record from you sqlce database.
if( has record//connected )
{
//Proceed to your insert statement remove if else and use
conn.Open();
cmd.ExecuteNonQuery()
//then check your DB again
}
else
{
//Problem on you connection string
}
Your sqlce database is located on your bin folder
Regards
i am using R.Net. in that i have done some database connection using R.Net in that i am getting the result in DataFrame format i need to convert it into DataSet
here is my code:
REngine.SetDllDirectory("#C:\Program Files\R\R-2.12.0\bin\i386")
engine = REngine.CreateInstance("RDotNet")
engine.EagerEvaluate("library(RODBC);")
engine.EagerEvaluate("con <- odbcConnect(dsn='rdsn', uid = 'sa', pwd = 'surya');")
cmdStr = SELECT DISTINCT Investment.InvestmentTypeCode,InvestmentTypeDescription, SortID FROM Investment,InvestmentTypeDef WHERE(Investment.InvestmentTypeCode = InvestmentTypeDef.InvestmentTypeCode) ORDER BY SortID
engine.EagerEvaluate("frm <- sqlQuery(con, '" + cmdStr + "');")
engine.GetSymbol("frm").AsDataFrame()
if any one knows plz help me...
There is not built-in functionality in R.Net or in the .NET Framework which can do that. But you can create and fill DataSets programmatically. So you will have to write your own conversion code.
See:
Creating A DataSet Programmatically
I recently had to convert a RDataFrame to a standard DataTable in C# - I'm assuming all the columns contain doubles:
public static DataTable RDataFrameToDataSet(DataFrame resultsMatrix) {
var dt = new DataTable();
var columns = new DataColumn[resultsMatrix.ColumnCount];
for (int i = 0; i < resultsMatrix.ColumnCount; i++) {
columns[i] = new DataColumn(resultsMatrix.ColumnNames[i], typeof(double));
}
dt.Columns.AddRange(columns);
for (int y = 0; y < resultsMatrix.RowCount; y++) {
var dr = dt.NewRow();
for (int x = 0; x < resultsMatrix.ColumnCount; x++) {
try {
dr[x] = resultsMatrix[y, x];
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
dt.Rows.Add(dr);
}
return dt;
}