jdbc connection of mysql to html - mysql

Hi i have the following file to connect mysql database to html files. But i am having trouble connecting it. Can anyone tell me where i find the locations.
What should i replace "jdbc:mysql://localhost/zulfiqar" with for it to work on my computer? where do i find this?
And is there anything else i have to change to make it work on my computer? this was a piece of code i found on the internet which i am trying to make work so i can understand how to do it, but i am struggling.
Thanks in advance!
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUserEnquiryForm extends HttpServlet{
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
/**Process the HTTP Get request*/
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException{
String connectionURL = "C:\Program Files(x86)\MySQL Server 5.0\bin\mysql.exe";
Connection connection=null;
ResultSet rs;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//get the variables entered in the form
String uId = req.getParameter("userId");
String fname = req.getParameter("firstname");
String sname = req.getParameter("surname");
String address1 = req.getParameter("address1");
String address2 = req.getParameter("address2");
String town = req.getParameter("town");
String county = req.getParameter("country");
String zipcode = req.getParameter("zipcode");
try {
// Load the database driver
Class.forName("org.gjt.mm.mysql.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection
(connectionURL, "root", "admin");
//Add the data into the database
String sql =
"insert into emp_details values (?,?,?,?,?,?,?,?)";
PreparedStatement pst =
connection.prepareStatement(sql);
pst.setString(1, uId);
pst.setString(2, fname);
pst.setString(3, sname);
pst.setString(4, address1);
pst.setString(5, address2);
pst.setString(6, town);
pst.setString(7, county);
pst.setString(8, zipcode);
int numRowsChanged = pst.executeUpdate();
// show that the new account has been created
out.println(" Hello : ");
out.println(" '"+fname+"'");
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: "
+ e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: "
+ e.getMessage());
}
catch (Exception e){
out.println(e);
}
finally {
// Always close the database connection.
try {
if (connection != null) connection.close();
}
catch (SQLException ignored){
out.println(ignored);
}
}

Some additional information about how it's failing might be useful.
1) Is it failing to make the socket connection (implying your service isn't running), or
2) Did it fail to initialize the driver? I'm not familiar with the one you listed. A more common alternative is "sun.jdbc.odbc.JdbcOdbcDriver".
3) Did you connect and simply fail authentication with user "root" and password "admin"?

What should i replace "jdbc:mysql://localhost/zulfiqar" with
Ans: It is the connection url. It does mean your MySQL database is running on localhost server (with default port) and you are connecting to 'zulfiqar' database. So first line under doPost() should be :
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Next, you are using org.gjt.mm.mysql.Driver driver for JDBC connection. It was initially developed by a hobbyist. It's later donated to MySQL where they renamed the package/classname. The old classname is kept for backwards compatibility reasons, but you should update it to com.mysql.jdbc.Driver and add mysql-connector-java-*-bin.jar in your WEB-INF/lib folder.
Next thing you are using :
connection = DriverManager.getConnection(connectionURL, "root", "admin");
So you are loading a connection from the connectionURL and accessing it with root user and admin password. Make sure these are correct in your case.
Last point is, you are inserting into emp_details table. Make sure you have this table already created in zulfiqar database with all required columns. And the number of '?' marks in the sql string should match the number of times you are doing pst.setString(index, data), otherwise you will get Invalid parameter index error.

Related

how can i connect to my database sql in a java class method and called it in another class?

i'm trying to create a desktop application using corba and java swing for graphical interface.
As you know , in CORBA we have to make the principal methods like: connecting to the database ,calculations... in the server ,so i have created a method in a server class for connecting to the database.
The java class method is the one shown bellow:
public void connect_db(){
// TODO Auto-generated method stub
JTextField txtUsername = FrameLogin.txtUsername;
JPasswordField pwd= FrameLogin.pwd;
JLabel lblLoginMessage= FrameLogin.lblLoginMessage;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/utilisateurs","root", "Mrayhana123");
Statement stm = conn.createStatement();
String sql="select * from etudiant where username='"+txtUsername+"' and pwd='"+pwd+"'";
ResultSet result = stm.executeQuery(sql);
if(result.next()){
lblLoginMessage.setText("you are connected");
lblLoginMessage.setForeground(Color.GREEN);
}
else {
lblLoginMessage.setText("Incorrect username or password!");
lblLoginMessage.setForeground(Color.RED);
}
} catch(Exception e){
//System.out.println("not connected to database");
e.printStackTrace();
}
}
And i have called it in the client class which contain the graphical interface by the following way:
public static JTextField txtUsername;
public static JPasswordField pwd;
public static JLabel lblLoginMessage = new JLabel("");
pnlBtnlogin.addMouseListener(new MouseAdapter() {
#Override
String username = txtUsername.getText();
String pwd= pwd.getText();
try {
SraCorbaImpl sci = new SraCorbaImpl();
sci.connect_db();
} catch(Exception e1){
//System.out.println("not connected to database");
e1.printStackTrace();
}
But the result always shows me Incorrect username or password! even though I type a username and a password which are in the database.
THANK YOU FOR HELPING ME
According to your comment, I understand that you are successfully connecting to the database but your query is not returning any rows.
If the code in your question is your actual code, then you are passing a JTextField to your [SQL] query and not the text of the JTextField. Likewise with the password. You are passing the JPasswordField and not the actual password.
Try the below code.
public void connect_db(){
JTextField txtUsername = FrameLogin.txtUsername;
JPasswordField pwd= FrameLogin.pwd;
JLabel lblLoginMessage= FrameLogin.lblLoginMessage;
try {
// Class.forName("com.mysql.cj.jdbc.Driver"); <- not required
Connection conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/utilisateurs","root", "Mrayhana123");
Statement stm = conn.createStatement();
String sql="select * from etudiant where username='"+txtUsername.getText()+"' and pwd='"+pwd.getText()+"'"; // Change here.
ResultSet result = stm.executeQuery(sql);
if(result.next()){
lblLoginMessage.setText("you are connected");
lblLoginMessage.setForeground(Color.GREEN);
}
else {
lblLoginMessage.setText("Incorrect username or password!");
lblLoginMessage.setForeground(Color.RED);
}
} catch(Exception e){
//System.out.println("not connected to database");
e.printStackTrace();
}
Because you are using string concatenation, the toString of JTextField is being inserted into your SQL string.
Consider using a PreparedStatement instead.
String sql="select * from etudiant where username=? and pwd=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, txtUsername.getText());
ps.setString(2, pwd.getText());
In that case, if you omit the .getText(), the code will not compile.

Database connectivity using mssql2008 and jdbc

So I have setup my code like so
public static Connection getConnection() {
try {
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=HRDB;
String user = "sa";
String pass = "r";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(dbURL, user, pass);
return conn;
} catch (ClassNotFoundException c) {
return null;
} catch (SQLException s) {
System.out.println(s.toString());
return null;
}
}
However, when I try to connect to the database I get the following exceptions.
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "java.lang.RuntimeException: Could not generate DH keypair".

set mysql connection behind ssh in groovy script SoapUI

From groovy script in SoapUI I need to connect to a mysql database to perform some queries. The problem is that due to security reasons no external access is possible.
Therefore it is required to get an ssh access (like a tunnel) and invoke mysql locally.
Initially I was reading the below project properties and then connect to mysql:
ServerUrl=jdbc:mysql://10.255.255.122:3306/db
ServerDbUser=user
ServerDbPwd=password
ServerDriver=com.mysql.jdbc.Driver
def url=testRunner.testCase.testSuite.project.getPropertyValue("ServerUrl")
def usr=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbUser")
def pwd=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbPwd")
def driver=testRunner.testCase.testSuite.project.getPropertyValue("ServerDriver")
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver(driver)
sqlServer = Sql.newInstance(url, usr, pwd, driver)`
But this didn't work so now it is required to establish first a ssh connection to the server with the IP 10.255.255.122 and then open the mysql connection locally. So I guess the Server Url will change to:
ServerUrl=jdbc:mysql://127.0.0.1:3306/db
But I don't know how to set first the ssh connection to the server.
Can someone help me with this?
Thanks.
Have a look at http://forum.soapui.org/viewtopic.php?t=15400 and connect to remote mysql database through ssh using java
It will give you an idea about implementing it in soapUI.
Below is the code by Ripon Al Wasim which is available as an answer at the stackoverflow link mentioned above
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

javafx connection to mysql [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
we are building javafx application which will be presenting information about stocks.
Here is the website:
http://analiza.host-ed.me/
But we've got a huge problem. Every free hosting doesn't allow remote mysql connection. And there is my question. When our site is on the server (which i linked) is this remote connection or local connection?
When we put this javafx app as a site it can't connect like it was on the local machine...
Is there any solution? Thanks for help.
(we need to use free hosting, because it's only a school project..)
You can access MySQL from JavaFX. But JavaFX runs on a client and something like php usually runs on a server. You will need a connection from your java app to MySQL. As your hosting provider won't allow you to directly connect to the database port from your Java Client App, you will need some other way to connect.
You could tunnel through port 80, you could run a servlet (or php server code, etc) to intercept incoming traffic and proxy database calls through a HTTP based REST interface or you could install the DB locally on the client.
I'm going to assume, for a school project, it's ok for each client machine to have it's own database. In which case, instead of using MySQL, use a lightweight Java database like H2, bundle it with your app by including it's jar as a dependent library, package the app plus DB jar as a signed WebStart application using the JavaFX packaging tools and host the files generated by the packaging tools at your hosting provider.
Update
Here is a sample application which uses a local H2 database on the client computer.
import java.sql.*;
import java.util.logging.*;
import javafx.application.Application;
import javafx.collections.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class H2app extends Application {
private static final Logger logger = Logger.getLogger(H2app.class.getName());
private static final String[] SAMPLE_NAME_DATA = { "John", "Jill", "Jack", "Jerry" };
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final ListView<String> nameView = new ListView();
final Button fetchNames = new Button("Fetch names from the database");
fetchNames.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
fetchNamesFromDatabaseToListView(nameView);
}
});
final Button clearNameList = new Button("Clear the name list");
clearNameList.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
nameView.getItems().clear();
}
});
VBox layout = new VBox(10);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
layout.getChildren().setAll(
HBoxBuilder.create().spacing(10).children(
fetchNames,
clearNameList
).build(),
nameView
);
layout.setPrefHeight(200);
stage.setScene(new Scene(layout));
stage.show();
}
private void fetchNamesFromDatabaseToListView(ListView listView) {
try (Connection con = getConnection()) {
if (!schemaExists(con)) {
createSchema(con);
populateDatabase(con);
}
listView.setItems(fetchNames(con));
} catch (SQLException | ClassNotFoundException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
private Connection getConnection() throws ClassNotFoundException, SQLException {
logger.info("Getting a database connection");
Class.forName("org.h2.Driver");
return DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
}
private void createSchema(Connection con) throws SQLException {
logger.info("Creating schema");
Statement st = con.createStatement();
String table = "create table employee(id integer, name varchar(64))";
st.executeUpdate(table);
logger.info("Created schema");
}
private void populateDatabase(Connection con) throws SQLException {
logger.info("Populating database");
Statement st = con.createStatement();
int i = 1;
for (String name: SAMPLE_NAME_DATA) {
st.executeUpdate("insert into employee values(i,'" + name + "')");
i++;
}
logger.info("Populated database");
}
private boolean schemaExists(Connection con) {
logger.info("Checking for Schema existence");
try {
Statement st = con.createStatement();
st.executeQuery("select count(*) from employee");
logger.info("Schema exists");
} catch (SQLException ex) {
logger.info("Existing DB not found will create a new one");
return false;
}
return true;
}
private ObservableList<String> fetchNames(Connection con) throws SQLException {
logger.info("Fetching names from database");
ObservableList<String> names = FXCollections.observableArrayList();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select name from employee");
while (rs.next()) {
names.add(rs.getString("name"));
}
logger.info("Found " + names.size() + " names");
return names;
}
}
There is a corresponding NetBeans project for this sample which will generate a deployable application. The project can be tested in webstart and applet mode.
For the sample, the database is stored on the user's computer (not the server from which the application was downloaded) and persists between application runs.
The exact location depends on the jdbc connection initialization string. In the case of my sample the database goes in the user's directory jdbc:h2:~/test, which is OS and User specific. In the case of me for Windows it ends up at C:\Users\john_smith\test.h2.db. Using a jdbc connection string such as jdbc:h2:~/test is preferable to a string such as jdbc:h2:C:\\Baza because a string with C:\\ in it is platform specific and won't work well on non-windows systems. For further information on h2 jdbc connection strings refer to the connections settings in the h2 manual.
The h2 system works such that if the database file already exists, it is reused, otherwise a new database file is created. If you modify the database, shut the application down, then load the application again a week later, it is able to read the data created the week before.

jsp mysql server connection timeout

hi i am doing an jsp project. and i deploy my project on apache tomcat. i use mysql as databese.
when i deploy project on remote server it is run good. but after some hours it gives me sql error. then i go back my apache server and start projecet again it run and after some hours it gives me same sql error again. i dont know the problem. is that caused from my java connection code or it is about mysql server. can some one tell me why it gives me sql error.?
public class ConnectionManager {
private String className = "com.mysql.jdbc.Driver";
private String userName ="username";
private String password = "password";
private String url = "jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8";
/**
* #uml.property name="connectionInstance"
* #uml.associationEnd
*/
private static ConnectionManager connectionInstance = null;
public ConnectionManager(){
}
public static synchronized ConnectionManager getInstance() {
if(connectionInstance == null) {
connectionInstance = new ConnectionManager();
}
return connectionInstance;
}
public Connection getConnection(){
Connection conn = null;
try {
Class.forName(className);
conn = DriverManager.getConnection (url, userName, password);
System.out.println("Connection Established");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
MySQL has a default connection timeout of 8 hours. So this means that you've kept a SQL connection open for too long. Your code suggests that you're creating only one connection on application's startup and reusing it application wide. This is very bad. This is not threadsafe.
You need to change your code so that you're not declaring and storing the SQL Connection as a static or instance variable anywhere in your code. Instead, it should be declared, created and closed within the shortest possible scope. Preferably within the very same method block as where you're executing the SQL query.
Here's a minor rewrite of your ConnectionManager which does the job properly:
public class ConnectionManager {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String USERNAME ="username";
private static final String PASSWORD = "password";
private static final String URL = "jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8";
static {
try {
Class.forName(DRIVER);
}
catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(DRIVER + " missing in classpath!", e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
Use it as follows:
public class SomeDAO {
public SomeEntity find(Long id) throws SQLException {
Connection connection = null;
// ...
try {
connection = ConnectionManager.getConnection();
// ...
}
finally {
// ...
if (connection != null) try { connection.close(); } catch(SQLException ignore) {}
}
return someEntity;
}
To improve connecting performance, use a connection pool instead of DriverManager.
See also:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
Are you closing connections properly after using them.