So Sorry if this Looks newbie Question, Im not Skilled in Mysql, I need to Get Entries of All Rows in My Mysql Database like We Do with Sqlite in Android :
Cursor mCursor = mDb.query("MyTable",new String[]{"My Column"},null,null.null,null);
ArrayList<> mylist = new ArrayList<>();
do{
mylist.add(mCursor.getString(mCursor.getColumnIndex("_id")));
while(mCursor.moveToNext());
How does This Work in Mysql Guys?
first you have to create connection to your database, You can use JDBC for it.
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
public Dbconnection()
{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","root","root");
}
catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
connection created in the constructor,
method to get all rows from a table
public void getData()
{
try{
ps=con.prepareStatement("select * from tbl_name");
rs=ps.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1)); //here you can get data, the '1' indicates column number based on your query
}
}
catch(Exception e)
{
System.out.println("Error in getData"+e);
}
}
In the while loop you can all data from rs using rs.getString(1)
NB: change column number for different column.
To get more idea please refer the links:
http://www.tutorialspoint.com/jdbc/index.htm
http://www.w3schools.com/sql/
Related
I'm trying to return a column of scores from a MS Access table using java. This is the table
I followed the guide from the java documentation.This is the result code
public class DatabaseConnector {
public static void main(String[] args){
Connection connection=null;
Statement statement =null;
ResultSet resultSet = null;
//Loads JDBC DRIVER
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
}catch (ClassNotFoundException cnfex){
System.out.println("There was a problem loading MS Access Driver");
cnfex.printStackTrace();
}
//Loads Database
try{
String scoredb="C:/Users/User/"+"/Documents/Database2.accdb";
String mydburl ="jdbc:ucanaccess://"+scoredb;
connection = DriverManager.getConnection(mydburl);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT CSC103, CSC103 FROM Scores");
while(resultSet.next()) {
Array z = resultSet.getArray("CSC103");
int[] CSC103 = (int[])z.getArray();
for (int i=0;i<CSC103.length;i++){
System.out.println(i);
}
}
} catch (SQLException sqlex){
sqlex.printStackTrace();
}
finally {
try{
if (null != connection) {
resultSet.close();
statement.close();
connection.close();
}
}catch (SQLException sqlex){
sqlex.printStackTrace();
}
}
I ended up getting the error-
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to [Ljava.lang.Object;
at org.hsqldb.jdbc.JDBCResultSet.getArray(Unknown Source)
at org.hsqldb.jdbc.JDBCResultSet.getArray(Unknown Source)
at net.ucanaccess.jdbc.UcanaccessResultSet.getArray(UcanaccessResultSet.java:184)
at DatabaseConnector.main(DatabaseConnector.java:28)
I have taken a look at this error online and it's a bit confusing because the solutions don't apply to database. How do I fix the error and get my values from the column?
ResultSet#getArray is used with databases that support special columns in which we can store an array of values for each row in the table. Access does not have an Array column type. The CSC103 column in your table contains a single ("scalar") value for each row, an integer in this case.
So you need to retrieve the individual values for each row and add them to a collection of some sort. The most straightforward way would be
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT CSC103 FROM Scores");
java.util.List<Integer> csc103List = new java.util.ArrayList<>();
while (rs.next()) {
csc103List.add(rs.getInt("CSC103"));
}
after which you'll have the values in an ArrayList<Integer>. If you really need an array of type Integer (which is a slightly different thing) then you can convert the List into an array like so:
Integer[] csc103Array = csc103List.toArray(new Integer[0]);
in my small test program I have some SQL Queries. The first SELECT * FROM kilometer; works properly and returns all the columns in the table. So in Java embedded, ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer;"); returns an ResultSet which is not empty.
Now I wanted to get only the rows within a specific date. But my embedded query ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer WHERE datum BETWEEN '2016-01-01' AND '2016-12-31';"); returns an empty ResultSet. But I've tested it online and it worked properly. Where is my mistake? I've consulted already some pages like this, but I can't find the mistake.
I am using SQLite 3.15.1 and Java SE 8.
Full java code:
public ArrayList<Strecke> getErgebnisse(final String startzeitpunkt, final String zielzeitpunkt) {
ArrayList<Strecke> strecken = new ArrayList<>();
try {
try {
if (connection != null) {
}
connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
if (!connection.isClosed())
} catch (SQLException e) {
throw new RuntimeException(e);
}
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer WHERE datum BETWEEN '2016-01-01' AND '2016-12-31';");
while (rs.next()) {
strecken.add(new Strecke(Instant.ofEpochMilli(rs.getDate("datum").getTime()).atZone(ZoneId.systemDefault()).toLocalDate(), rs.getString("startort"), rs.getString("zielort"), rs.getDouble("kilometer")));
}
rs.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return strecken;
}
First of all I would recommend that you use prepared statements while executing your queries instead of passing the query directly as a string......secondly I believe the problem here is that you are passing the date as a string in quotes and not a date.....I think that is the issue here. You would need to use sqllites datetime functions for this....
I am working on a project "Hospital Management System" in java swing. Now I have a text field whose value is supposed to be increased by one whenever page loads. It basically contain the value of patient Id. Now I want to retrieve the maximum or last value from database and increase it by one and want to set that value in a text field whose variable is "textField_1". Here table name is "patient" and column name is "patid" and this snippet is written in page load event. Select query is successfully executed but the problem is not fetching the maximum value from the database. Control reached in the if block but it's not printing the value if "i". Please help!!
try
{
Connection con;
Statement st;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("Jdbc:Odbc:hos_man");
st=con.createStatement();
rs=st.executeQuery("select * from patient where patid = (select max(patid) from patient);");
if (rs.next()==true)
{
int i=rs.getInt(1);
i++;
textField_1.setText(""+i);
}
else
{
textField_1.setText(""+100);
}
con.close();
st.close();
rs.close();
}
catch (Exception e)
{
}
Firstly your Query is right, but its bad practice. if you need only max(patid) then use this query:
select max(patid) from patient
Then modify your code like below.
try
{
Connection con;
Statement st;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("Jdbc:Odbc:hos_man");
st=con.createStatement();
rs=st.executeQuery("select max(patid) from patient");
int i=100;
while (rs.next())
{
i=rs.getInt(1);
}
textField_1.setText(""+i);
con.close();
st.close();
rs.close();
}
catch (Exception e)
{
e.printStackTrace();
}
This should work
public class StudentDataPersistence {
public void insertStudentInfo(Student student) {
String url = "jdbc:oracle:thin:#localhost:1521:XE";
String username = "system";
String password = "Data03#";
Connection connection = null;
//Statement statement = null;
try {
//Step 1 : Register JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Step 2 : Open a connection
System.out.println("Connecting to a selected database...");
connection = DriverManager.getConnection(url, username, password);
if (connection != null) {
System.out.println("Connected to oracle");
}
//Step 3 : Write code to map Java Object to the Student_Info table
System.out.println("Inserting records into the database");
statement = connection.createStatement();
String sql = "insert into Student_Info " +
"VALUES(student.getName(),student.getRoll_no(),student.getAddress(),student.getPhone_no())";
statement.executeUpdate(sql);
System.out.println("Inserted student information into the database");
} catch (SQLException se) {
//handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
//Handle errors for Class.forName
} finally {
System.out.println("Inside the finally block");
//finally block used to close resources
try {
statement.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
connection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("!GoodBye");
}
public static void main(String[] args) {
Student student = new Student("Bavin", 1, "Umar Nagar", "89898989809");
StudentDataPersistence obj = new StudentDataPersistence();
obj.insertStudentInfo(student);
}
}
The error it shows it :
Connecting to a selected database...
Connected to oracle
Inserting records into the database
java.sql.SQLException: ORA-00904: "STUDENT"."GETPHONE_NO": invalid identifier
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:189)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:242)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:554)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1478)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:888)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2076)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1986)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2697)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1035)
at org.core.hibernate.reason.StudentDataPersistence.insertStudentInfo(StudentDataPersistence.java:52)
at org.core.hibernate.reason.StudentDataPersistence.main(StudentDataPersistence.java:80)
Inside the finally block
!GoodBye
All the answers (those of you who illustrate it with an oracle query) in reply were wrong.
Kindly do have a look at it before posting.
the correct one i got when i posted another thread regarding the same:
String query = "insert into Student_Info(name,roll_no,address,phone_no) VALUES('"+student.getName()+"',"+student.getRoll_no()+",'"+student.getAddress()+"','"+student.getPhone_no()+"')";
you have commented out your Statement object definition. So the statement object is unknown when you're using it.
uncomment this line:
//Statement statement;
And as earlier pointed out by #putaro, you need to quote certain parts of your SQL query.
String sql = "insert into Student_Info " +
"VALUES("+student.getName()+","+student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
This is to insert the actual object values into the query. Things within the quote would be inserted as it is.
Error ORA-00904 means Oracle does not know the identifier "STUDENT"."GETPHONE_NO" it looks like you are trying to insert some value to a column named "GetPhone_NO" to Table "Student" from your SQL. so you should check your SQL and table structure again
I see there are two problems in the code.
Currently your code is not using the student object while making the query. All student.getName() etc call taken as plain strings rather than method calls that returns the appropriate values.
Second it would be better to write the query in the following form. It will avoid silly errors because of the structure of the tables.
"INSERT INTO student_info(name,roll_no,address,phone) VALUES("+
student.getName()+"," +
student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
Even better is if you use prepared statement like
Try changing the query like
"INSERT INTO student_info(name,roll_no,address,phone) VALUES(?,?,?,?)"
and then set the parameter values.
I'm trying to scroll over all the contents of a database. How do I properly do this:
conc conclass = new conc();
Connection conn = conclass.dbConnect();
try{
Statement statement=conn.createStatement();
ResultSet rs;
String sql;
rs=statement.executeQuery("SELECT * FROM q_table");
if(rs.next()){
String yo=rs.getString("Question");
jTextArea1.setText(yo);
}
}catch(Exception e){e.printStackTrace();}
And here's my class for connecting to the database:
public Connection dbConnect() {
try {
String db_connect_string="jdbc:mysql://localhost:3306/questions";
String db_userid="root";
String db_password="1234";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
What is wrong with my code? It loads the first record when I click on the scroll button. But when I click it again. It doesn't do anything at all.
To collect all results from table (I assume you mean the table rather than the whole database):
while(rs.next()) {
String yo=rs.getString("Question");
// add 'yo' to a list or similar...
}
You need to iterate across your ResultSet. The ResultSet scrolls over each row returned from the database in sequence. See this example for more details.
You need to keep the Resultset open. For every click on the button, you must call rs.next() once. After that, a new row will copied into the ResultSet.