i have some issue How i can retrieve config.ini--->[odbc] database connection into my getconnection class ? i'm using mysql database
i storage the connection into my database and Config.ini--[odbc] is fine
but when i want to retrive and connect my database into application trow config.ini i can't
check this is my database class :
public class DB(
public static String url = "jdbc:mysql://localhost/resturno?useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8";
public static String user = "root";
public static String paw = "";
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(url, user, paw);
} catch (ClassNotFoundException | SQLException ex) {
System.out.println(ex.getMessage());
System.out.println("couldn't connect!");
throw new RuntimeException(ex);
}
}
)
and this is my Config.ini :
[ODBC]
ServerName = jdbc:mysql://localhost
DataBase = resturno?useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
Username = root
Password =
Year = 2019
and this is my readIni class :
public void readIni() {
try {
File file = new File(pathIni);
if (file.exists()) {
Wini wini = new Wini(new File(pathIni));
String url = wini.get("ODBC", "ServerName");
String dbnm = wini.get("ODBC", "DataBase");
String dbus = wini.get("ODBC", "Username");
String dbpas = wini.get("ODBC", "Password");
String dbyer = wini.get("ODBC", "Year");
if ((url != null && !url.equals("")) && (dbnm != null && !dbnm.equals("")) && (dbus != null && !dbus.equals("")) && (dbpas != null && !dbpas.equals("")) && (dbyer != null && !dbyer.equals(""))) {
Serverurl.setText(url);
dbname.setText(dbnm);
dbuser.setText(dbus);
dbpass.setText(dbpas);
dbyear.setText(dbyer);
}
}
} catch (IOException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
}
if you have anything missing i'll help me on my code
You are probably missing the port of your Database.
public static String url = "jdbc:mysql://localhost:<PORT>/resturno?useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8";
Usually the port is 3306. I hope this helps you.
Related
I am trying retrieve keys for a table on a MySQL database using DatabaseMetaData and trying to use InformationSchema to do it. MySQL Configuration Properties
import java.sql.*
class DataLoader {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"
static final String DB_URL = "jdbc:mysql://localhost:3306/mydb?useInformationSchema=true"
static final String USER = "user"
static final String PASS = "password"
static final String DB = "mydb"
public static void main(String[] args) {
Connection conn = null
Statement stmt = null
try {
Class.forName(JDBC_DRIVER)
conn = DriverManager.getConnection(DB_URL, USER, PASS)
println "Database Product Name: " + conn.getMetaData().getDatabaseProductName()
println "Database Product Version: " + conn.getMetaData().getDatabaseProductVersion()
println "JDBC Driver: " + conn.getMetaData().getDriverName()
println "Driver Version: " + conn.getMetaData().getDriverVersion()
ResultSet importedKeysRS = conn.getMetaData().getImportedKeys(DB, null, "user")
} catch (Exception e) {
e.printStackTrace()
} finally {
try {
if (stmt != null) {
stmt.close()
conn.close()
}
} catch (SQLException se) {
}// do nothing
try {
if (conn != null)
conn.close()
} catch (SQLException se) {
se.printStackTrace()
}
}
}
}
When I execute the above groovy code, the following is the exception thrown.
Database Product Name: MySQL
Database Product Version: 5.6.15-rel63.0-log
JDBC Driver: MySQL-AB JDBC Driver
Driver Version: mysql-connector-java-5.1.6 ( Revision: ${svn.Revision} )
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'REFERENCED_TABLE_NAME' in where clause is ambiguous
at com.mysql.jdbc.DatabaseMetaDataUsingInfoSchema.executeMetadataQuery(DatabaseMetaDataUsingInfoSchema.java:50)
at com.mysql.jdbc.DatabaseMetaDataUsingInfoSchema.getImportedKeys(DatabaseMetaDataUsingInfoSchema.java:780)
When I remove useInformationSchema=true property from the JDBC URL, it works with no errors but takes too long to execute getImportedKeys()
How can I enable useInformationSchema?
If I cannot use property useInformationSchema, what can I do to make queries like getImportedKeys() and getExportedKeys() run faster?
String url = "jdbc:mysql://localhost:3306/mysql";
String user = "root";
String pass = "root1";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, pass);
System.out.println("Connected to database");
} catch (Exception e) {
System.out.println(e);
System.out.println("Could not connect to database");
}
Password should be "root". The program does not display the message in the catch block and stops working. Can anyone tell me what happens?
[UPDATE]
I apologise I asked a bad question. The problem is already solved, Thanks. This helps to properly check whether the connection exists.
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
There are three different ways to connect to SQL data base as shown in below code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MySQLConnectExample {
public static void main(String[] args) {
// creates three different Connection objects
Connection conn1 = null;
Connection conn2 = null;
Connection conn3 = null;
try {
// connect way #1
String url1 = "jdbc:mysql://localhost:3306/test1";
String user = "root";
String password = "secret";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
// connect way #2
String url2 = "jdbc:mysql://localhost:3306/test2?user=root&password=secret";
conn2 = DriverManager.getConnection(url2);
if (conn2 != null) {
System.out.println("Connected to the database test2");
}
// connect way #3
String url3 = "jdbc:mysql://localhost:3306/test3";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "secret");
conn3 = DriverManager.getConnection(url3, info);
if (conn3 != null) {
System.out.println("Connected to the database test3");
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
I use apache mina sshd to set up a mocked ssh server for Junit testing purpose. Since the documentation for apache mina is quite unclear, I cannot figure out how to deal with authentication problem in testing.
Code I would like to test, basically using Jsch to transfer file from local to remote.
public static void scpTo(String rfilePath, String lfilePath, String user, String host, String keyPath, int port) {
FileInputStream fis=null;
try {
while(true) {
String rfile = rfilePath;
String lfile = lfilePath;
JSch jsch = new JSch();
jsch.addIdentity(keyPath);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
Session session = jsch.getSession(user, host, port);
session.setConfig(config);
session.connect();
// exec 'scp -t rfile' remotely
String command = "scp " + " -t " + rfile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
if (checkAck(in) != 0) {
System.exit(0);
}
File _lfile = new File(lfile);
if(!_lfile.exists()) {
System.err.println("Local file not existing");
}
//check file existing
File _rfile = new File(rfile);
if (_rfile.exists()) {
System.out.println("Remote file already existed");
break;
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize = _lfile.length();
command = "C0644 " + filesize + " ";
if (lfile.lastIndexOf('/') > 0) {
command += lfile.substring(lfile.lastIndexOf('/') + 1);
} else {
command += lfile;
}
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
System.exit(0);
}
// send a content of lfile
fis = new FileInputStream(lfile);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0) break;
out.write(buf, 0, len); //out.flush();
}
fis.close();
fis = null;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
System.exit(0);
}
out.close();
channel.disconnect();
session.disconnect();
//System.exit(0);
Thread.sleep(2000);
}
} catch (Exception e) {
System.out.println(e);
try {
if (fis != null) fis.close();
} catch (Exception ee) {
}
}
}
And the setUp used for testing. If I would like to authenticate all the user & host pairs by using a given key file in my resource folder, what should I do for setUp? For the current setUp, it will have Auth fail error.
#Before
public void setup() {
user = "siyangli";
host = "localhost";
//pick a port not occupied for tesing
port = 22998;
sshd = SshServer.setUpDefaultServer();
sshd.setPort(port);
keyPath = "/Users/siyangli/.ssh/id_rsa";
//it will change the key file??? do not know why, how to work around the authentication key??
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[]{"/Users/siyangli/.ssh/id_rsa"}));
//sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(keyPath));
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
public boolean authenticate(String username, String password, ServerSession session) {
return true;
}
});
sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
#Override
public boolean authenticate(String username, PublicKey key, ServerSession session) {
return true;
}
});
CommandFactory myCommandFactory = new CommandFactory() {
public Command createCommand(String command) {
System.out.println("Command: " + command);
return null;
}
};
sshd.setCommandFactory(new ScpCommandFactory(myCommandFactory));
List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
userAuthFactories.add(new UserAuthPassword.Factory());
sshd.setUserAuthFactories(userAuthFactories);
List<NamedFactory<Command>> namedFactoryList = new ArrayList<NamedFactory<Command>>();
namedFactoryList.add(new SftpSubsystem.Factory()); sshd.setSubsystemFactories(namedFactoryList);
try {
sshd.start();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("Finished setup !!! ");
}
You need to change this line:
userAuthFactories.add(new UserAuthPassword.Factory());
to
userAuthFactories.add(new UserAuthPublicKey.Factory());
i have a signup.jag (jaggery page) for user to register.
i have a signup.js (javascript) for javascript validation.
i want to store the user info in mysql database through java i.e. jdbc for which i have written the following code with file name sigunp.java :
import java.io.*;
import java.lang.*;
import java.sql.*;
import java.servlet.*;
import java.servlet.http.*;
public class signupdb extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException IOException
{
response.setContentType(text/html);
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost:3306/ticketing";
Connection connection;
try
{
String firstname = request.getParameter("fname");
String lastname = request.getParameter("lname");
String phonenum = request.getParameter("phone");
String addr = request.getParameter("address");
String email = request.getParameter("email");
String password = request.getParameter("pass");
pw.println(firstname);
pw.println(lastname);
pw.println(phonenum);
pw.println(addr);
pw.println(email);
pw.println(password);
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionurl,"root","suselinux");
PreparedStatement pst = connection.prepareStatement("insert into userinfo values(?,?,?,?,?,?)");
pst.setString(1,firstname);
pst.setString(2,lastname);
pst.setString(3,phonenum);
pst.setString(4,addr);
pst.setString(5,email);
pst.setString(6,password);
int i = pst.executeUpdate();
if(i != 0)
{
pw.println("<br>Record has been inserted");
}
else
{
pw.println("No Data Inserted");
}
}
catch(Exception e)
{
pw.println(e);
}
}
}
But when i started the jaggery server and submitted the data it showed me error 404.
finally i resolved it !
i created a con.jag file which has table named users :
<%
var query1 = "create table users (id int not null auto_increment, primary key(id), first_name varchar(15), last_name varchar(15), phone varchar(20), address varchar(50), email varchar(30), pass varchar(30));";
config();
var db = new Database ("jdbc:mysql://localhost:3306/tickets", "root", "password", config);
try
{
db.query(query1);
print("Table Created again");
} catch (e)
{
print(e.toString());
}
finally
{
db.close()
}
%>
then inserted the data into the database with insert_data.jag file :
<%
var frst_name = request.getParameter('fname');
var lst_name = request.getParameter('lname');
var country_name = request.getParameter('country_code');
var phon = request.getParameter('phone');
var addr = request.getParameter('address');
var mail = request.getParameter('email');
var pwd = request.getParameter('pass');
var data = "insert into users(first_name, last_name,country, phone, address, email, pass) values ('"+frst_name+"','"+lst_name+"','"+country_name+"', '"+phon+"','"+addr+"','"+mail+"','"+pwd+"')";
config();
var db = new Database ("jdbc:mysql://localhost:3306/tickets", "root", "password", config);
try
{
db.query(data);
} catch(e)
{
print(e.toString());
} finally
{
db.close()
}
%>
It really works fine !
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();
}
}
}