Access Wamp Server Database from Eclipse - java

I want to access my Wamp Server database which is in my computer with using Java. My code is below:
public static void main(String[] args)
{
try
{
// create our mysql database connection
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/deneme";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM users";
// create the java statement
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
int id = rs.getInt("id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
Date dateCreated = rs.getDate("date_created");
boolean isAdmin = rs.getBoolean("is_admin");
int numPoints = rs.getInt("num_points");
// print the results
System.out.format("%s, %s, %s, %s, %s, %s\n", id, firstName, lastName, dateCreated, isAdmin, numPoints);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
After this, it gives me this error:
Got an exception!
com.mysql.jdbc.Driver
How can I connect my database in my own computer to java?
Thanks.

Try to add the mysql-connector-java-xxxx-bin.jar in the /lib folder.
You can download it from here.
And right click on project properties --> Java Build Path --> External jar

Related

Java JDBC throwing an error for an SQL query asking to return details from only particular rows

I have a database called 'airplane' inside which there is a table named booking.
The booking table has the columns phone(int type) ,name(text type),address(text type),city(text type) destination(text type),date(text type). I want to fetch only the rows whose phone column has value or data equal to phone number entered by the user . I wrote the following code for it . For context , I am using java using JDBC
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/airplane";
static final String USER = "root";
static final String PASS = "";
Connection conn = null;
try
{
System.out.println("enter cell no");
int cell=sc.nextInt();
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
// My SQL SELECT query.
String query = "SELECT * FROM `booking` where phone=cell";
// creating the java statement
Statement st = conn.createStatement();
/** executing the query, and getting a java resultset of all rows whose phone
column has the value equal to one entered by user and stored by me in
int variable cell**/
ResultSet rs = st.executeQuery(query);
//iterate through the java resultset
while (rs.next())
{
int Phone = rs.getInt("phone");
String Name = rs.getString("name");
String Address = rs.getString("address");
String City = rs.getString("city");
String Destination = rs.getString("destination");
String Date = rs.getString("date");
// print the results
System.out.format("%d, %s, %s, %s, %s, %s\n", Phone, Name, Address, City, Destination, Date);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
I am getting the error:
Got an exception!
Unknown column 'cell' in 'where clause'
What am I doing wrong?
Try this:
String query = "SELECT * FROM `booking` where phone=" + cell;
A better way to handle this is to use PreparedStatement
This case, the query would look like:
String query = "SELECT * FROM `booking` where phone=?"
and
statement.setInt(1, cell);
you will see it's gonna run
String query = "SELECT * FROM booking where phone="+"\"%s\"";
query=String.format(query,cell);

Can't Show database on XAMPP-> mysql to java

I am using XAMPP->Mysql to create database and using Netbeans IDE 8.1 fro create java
My Code
//default package
//1st step
import java.sql.*;
public class DemoJDBC {
public static void main(String[] args) {
try{
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
rs.next();
String name = rs.getString("sname");
System.out.println(name);
//6th step
con.close();
}
catch (Exception e){
}
}
}
Why it didn't show output name ? It just show
"BUILD SUCCESSFUL (total time: 1 second)" in netbeans output
You need to loop through the ResultSet to get the tuples or rows. So while looping you retrieve whatever data or field you want to get. try:
public static void main(String[] args) {
try {
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
//6th step
con.close();
} catch (Exception e) {
}
}
NOTE if by default you did not change the password of the root user it is just the empty String (thus "" and not "0"). Other than that you know what you are doing.
Along with the correction of your code to loop through the ResultSet, you also need to correct your connection string as shown below:
Considering that your MySQL is running on the default MySQL port 3306 (which I see that you already are), the connection string needs to be updated.
Also saw that password for the user root is '0', is it really the password?
public static void main(String[] args) {
try {
String query = "SELECT * FROM Student";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "0");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
con.close();
} catch (Exception e) {
}
}
Also ensure to have your MySQL Connector/J jar file to be present in your CLASSPATH to not to face any reference issues.
Hope that this helps!

Netbeans java application - executing query on MySql database

In the project I'm working on I need to execute Searching SQL query i.e the wildcard characters in Java Netbeans.
I'm able to execute simple queries like
String driver = "jdbc:mysql://localhost/techo";
String un = "root";
String pw = "root";
String empid = id.getText();
try{
Connection con = DriverManager.getConnection(driver,un,pw);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select*from employees where empid ="+empid+"");
while(rs.next())
{
String name = rs.getString("name");
String salary = rs.getString("salary");
name1.setText(name);
salary1.setText(salary);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
This works completely fine. But now I want to use this MySql query
Mysql>select * from employes where empid like "123%";
instead of this
Mysql>select * from employes where empid =123;
in java Netbeans.
I've tried to do this
String driver = "jdbc:mysql://localhost/techo";
String un = "root";
String pw = "root";
String empid = id.getText();
try{
Connection con = DriverManager.getConnection(driver,un,pw);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid%+"");
while(rs.next())
{
String id = rs.getString("EmpId");
String name = rs.getString("name");
String salary = rs.getString("salary");
area.setText(id +" "+name+" "+salary+" "+ "\n");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
As you can see that in the 8th line I've inserted the wildcard character(%) but this ain't working. How can I solve this?
Your wildcard character is misplaced.
It should be:
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid+"%");
In this case the % char will be treated as a wildcard.
If you want to search the % char itself, you have to escape it following the mysql escape rules:
ResultSet rs = stm.executeQuery("select*from employees where empid like \""+empid+"%%\"");
Pay special attention to the quotes

How to call parameterized stored procedure in jdbc

I need to call a parameterized stored procedure in java jdbc from sql server.
The stored procedure goes like this in sql
create proc patientreg
#id int
as
begin
select [patient_id],[Psurname], [pFirstname], [pMiddlename], [reg_date], [DOB], [Sex], [Phone_num], [Addr],[Email],[dbo].[fncomputeage](DOB) from [dbo].[Patient_registration] where [patient_id] = #id
end
please note dbo.fncompute(DOB) is a function
To call it in JDBC:
try{
String str = "{call patientreg(?)}";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbcdbc:GeneralHospital");
cstmt = con.prepareCall(str);
cstmt.setInt(1, Integer.parseInt(t.getText()));
cstmt.execute();
int pid = cstmt.getInt(1);
String sname = cstmt.getString(2);
String fname = cstmt.getString(3);
String mname = cstmt.getString(4);
String regdate = cstmt.getString(5);
String dob = cstmt.getString(6);
String sex = cstmt.getString(7);
String phonenum = cstmt.getString(8);
String address = cstmt.getString(9);
String email = cstmt.getString(10);
int age = cstmt.getInt(11);
l1.setText(sname+""+ fname+""+mname);
l3.setText(Integer.toString(pid));
l4.setText(regdate);
l5.setText(dob);
l6.setText(Integer.toString(age));
l7.setText(sex);
l8.setText(phonenum);
l9.setText(address);
l10.setText(email);
cstmt.close();
}
catch(Exception ex)
{
System.out.println("Error occured");
System.out.println("Error:"+ex);
}
After doing it this way it throwing an exception:
Error:java.sql.SQLException: Parameter 1 is not an OUTPUT parameter
there is a couple of problems with your code.
First, Don't use the jdbc odbc driver! It is unstable, and might not work correctly. Use Microsoft's own jdbc driver, or, even better, use jTDS, which is an excellent open source jdbc driver for Sql Server.
Second, the getInt, getString etc methods on CallableStatement is used to retrieve output parameters from the stored procedure. What you have is an ordinary resultset.
CallableStatement cstmt = con.prepareCall("{call patientreg(?)}");
// add input parameter
cstmt.setInt(1, someInteger);
// execute and get resultset.
ResultSet rs = cstmt.executeQuery();
// read resultset
while (rs.next()) {
int pid = rs.getInt(1);
String sname = rs.getString(2);
String fname = rs.getString(3);
// etc.
}
// remember to close statement and connection
try this
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?");
cs.setString(1, "val1");
cs.setString(2, "val2");
rs = cs.executeQuery();
ArrayList<YourClass> listYourClass = new ArrayList<YourClass>();
while (rs.next()) {
YourClassret= new YourClass();
ret.set1(rs.getString(1));
ret.set2(rs.getString(2));
ret.set3(rs.getString(3));
listaObjectX.add(ret);
}
return listYourClass ;
} catch (SQLException se) {
System.out.println("Error "+ se.getMessage());
se.printStackTrace();
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
//do ex.print
}
}

How to change the database name and table using java?

i try to understand this part of code:
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("mysqlpassword");
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st = conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
i understand that test database is a default database. but if i want to use an existing database, i will just modify test to another database name isn't it?
If yes how do i modify my code if my new database is Test2 with table name Email which contains mail column with varchar(100)
i try to replace test by Test2 Email_list by Email but i don't know where to put the column name mail.
Thank you for help
The INSERT statement you use omits the columns.
INSERT INTO tablename VALUES (1, 2, 3)
can be written if the table has three columns and for all three columns values are provided.
If some columns can be left empty or have default values, you can write
INSERT INTO tablename (column1, column2) VALUES (1, 2)
In this cas the value for column3 is null or the default value.
So in your case the column name is put nowhere.
You are missing PORT number in your connection string...
String url = "jdbc:mysql://localhost/test"; should be String url = "jdbc:mysql://localhost:PORT_NUMBER/test"; like String url = "jdbc:mysql://localhost:3306/test";
Let me know if you have any queries...
Also, Check below how Prepared Statement works
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Good Luck!!!

Categories

Resources