PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label connection. Show all posts
Showing posts with label connection. Show all posts

Thursday, April 21, 2022

[FIXED] How do I check if I'm connected to database?

 April 21, 2022     conditional-statements, connection, mysql, php     No comments   

Issue

This is the code to connect to the mysql database:

$con = mysql_connect("", "", "");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("", $con);

I want to echo 'connected'/'disconnected' depending on state.

How can it be done?


Solution

Do it Like this

if ($con) {
  echo 'connected';
} else {
  echo 'not connected';
}

Or try this

echo $con ? 'connected' : 'not connected';


Answered By - Danil Speransky
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to fix: Anylogic does not connect to Eclipse over Socket

 April 21, 2022     anylogic, connection, interface, java, sockets     No comments   

Issue

I'm trying to create a scenario on my Macbook with Mojave in Anylogic, which is part of agent-based simulation with many different tools. My idea is to connect Anylogic via Java Interface to Eclipse. The main problem is, that Anylogic somehow does not respond.

I have tried many different codes with sockets, but could not find one, which worked for Anylogic. I'm using the free version of Anylogic and created a Java Interface under my Main Project. To run the Java Interface I press right-click on the file and select 'run with Java Editor'

In comparison to that I create two files in Eclipse, with one being the Server and one the Client and it worked.

so this is my Eclipse, which I guess should be fine https://www.minpic.de/i/7wbk/nv00b

this is my main model in Anylogic https://www.minpic.de/i/7wbn/pzuut

and there is the Java interface with the server code in it. https://www.minpic.de/i/7wbo/1mxsl4

Im pretty new to coding so hopefully you guys can help me.


public class server{
    public static void main(String[] args) throws IOException {
    ServerSocket ss = new ServerSocket(4995);
    Socket s = ss.accept();

    System.out.println("Client connected");
    DataInputStream dout = new DataInputStream(s.getInputStream());
    BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    while(true) {
        String yoo = dout.readUTF();
        System.out.println("client" + yoo);
        if(yoo.equalsIgnoreCase("exit"));
        break;
    }
    ss.close();

    }   
}


public class client{
    public static void main(String[] args) throws IOException {
    Socket s = new Socket("localhost",4995);
    DataOutputStream dout = new DataOutputStream(s.getOutputStream());
    BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    while (true)
    {
        String so= br.readLine();
        dout.writeUTF(so);
        System.out.println("client" + so);
        if(so.equalsIgnoreCase("exit"));
        break;
    }
    s.close();
        }
    }

I was expecting the consoles of both programs to show me messages I have send via the console, but neither of the programs show me the messages of what I wrote in the other program.


Solution

The Java code itself is fine, at least for creating a simple connection. For the server side in Eclipse, you can leave it like that.

For the client side in AnyLogic however, there is an issue: You can't run the code directly like this, because you have a main method in there. AnyLogic is no "normal" Java IDE like Eclipse, it is a very specific IDE. It automatically creates you exactly one project and puts everything in there that is needed to run it, including one main method. This means you don't need a second main method. You rather have to make your client become "part" of the bigger programm that AnyLogic is building for you. When you clicked on "Open with Java Editor" that only showed you the code, you cannot run any code like that in AnyLogic!

Therefore we do the following steps:

  1. Create of a Java class (a simple one, without main method) Client in AnyLogic
  2. Add a function to the class to start the client procedure (before it was triggered by it's own main method)
  3. Create an instance from the Class Client

The class code, already including the function is the following:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Client implements Serializable {

    public Client() {
    }

    public void activate() {
        try {
        Socket s = new Socket("localhost",4995);
        DataOutputStream dout = new DataOutputStream(s.getOutputStream());
        BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
        while (true)
        {
            String so= br.readLine();
            dout.writeUTF(so);
            System.out.println("client" + so);
            if(so.equalsIgnoreCase("exit"));
            break;
        }
        s.close();
        }
        catch(IOException e) {
            System.out.println(e);
        }
    }

    /**
     * This number is here for model snapshot storing purpose<br>
     * It needs to be changed when this class gets changed
     */ 
    private static final long serialVersionUID = 1L;

}

Creating the instance and activating the client can be done with this code, add it for example in a button or the OnStartup code of the AnyLogic Main Agent:

Client client = new Client();
client.activate();

Button



Answered By - Florian
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use javascript to run automated tests in browser using selenium+CUCUMBER

 April 21, 2022     connection, cucumber, javascript, selenium, testing     No comments   

Issue

Well, I am kinda new to this. First of all, my main goal is to execute a simple cucumber example which tests automatically something extremely simple as well.By doing this I will try to get the idea of how should i do other kind of autmated test. So, I wrote some scenarios, and I want to test them somehow on a site(e.g. google.com). The site is written in JS and therefore I need to write JavaScript code to "connect" the scenarios with the language.

I google searched things like: "How to automatically test a site using cucumber" "How to automatically run scenarios with selenium-javascript" and so on...

Any ideas? No hatefull comments please :/ Thanks in advance!

DL.


Solution

I wrote some scenarios,

When you say that I believe you are able to execute your testcases with cucumber

The site is written in JS and therefore I need to write JavaScript code to "connect" the scenarios with the language.

thats not necessary, if you are site is based on javascript like AngularJS you can still use simple java + selenium but protractor is recommended for same as it have wrapper. protractor is a nodejs based project to deal with sites based on AngularJS.

https://www.protractortest.org/#/

How to automatically test a site using cucumber

You can use a CI/CD tool like jenkins which you can trigger manually or you can put an scheduler who will run all your test script against your website on it. You can also turn on the notification so when ever the test complete it will shoot an email to respective individuals

Refer:

https://jenkins.io/

You can get n number of tutorial regarding same. example:

Click Here



Answered By - Shubham Jain
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How nodejs can maintain multiple concurrent connections?

 April 21, 2022     connection, node.js, persistent-connection     No comments   

Issue

I was reading a lot about nodejs but still not clear about following :

  • With TCP protocol client and server agree on one port and then can maintain a connection. Server knows IP address of client and hence can send back messages. If we use nodejs then multiple clients can connect to same nodejs server on same port. How this can be possible? How multiple connections can be established on same port by same server.
  • If client is behind NAT then its IP can be dynamic, so how can nodejs server can send data to client.
  • What will be resource utilization in maintaining persistent connections on server and client ?
  • What happend when nodejs server crashes? How can client initiate connection again ?
  • If there is network problem on client side and it terminates and initiate connection after every 5 mins ..then is there a way this scenario can be handled?

Solution

With TCP protocol client and server agree on one port and then can maintain a connection.Server knows IP address of client and hence can send back messages.If we use nodejs then multiple clients can connect to same nodejs server on same port. How this can be possible? How multiple connections can be established on same port by same server.

There is no limitation to the number of connections which can be maintained on a single port (although, in practice, there may be operating system or hardware limitations). Of course, only a single process can listen on a port, but that has nothing to do with connections. That's not node-specific, all TCP servers work like that.

If client is behind NAT then its IP can be dynamic , so how can nodejs server can send data to client.

You're essentially asking how NAT works. Again, there's nothing node-specific in this case. The NAT server simply alters packet headers as necessary, and maintains translation tables for routing, just like with any connection.

What will be resource utilization in maintaining persistent connections on server and client

The overhead is really quite minimal for just the connection itself. A little bit of memory, but almost insignificant in the big picture. If you're storing additional associated data with each connection, that may be different. Node.js handles large number of concurrent connections very well, but if you're concerned, you can always search for benchmark tests, or write your own.

What happend when nodejs server crashes?How can client initiate connection again?

Sockets emit both close and error events. Simply listen for them, and attempt to reconnect afterwards, probably with a back-off delay.

If there is network problem on client side and it terminates and initiate connection after every 5 mins ..then is there a way this scenario can be handled?

Not entirely sure what you're asking here. The client simply needs to reconnect as stated in the previous question/answer. If you're associating certain data with a client socket, and you want a grace period where the client has a chance to reconnect before that data is freed, then you'll need to set a timeout which will free those resources after a certain amount of time. Then, in the connection listener, or perhaps on an authentication event, you'll want to analyse the new connection to see if it matches a recently disconnected client.

I would definitely recommend looking at socket.io, especially if your use case is web-based, although it can be used for more than just browser/server connections. It will do a lot of the things you seem to be concerned about (reconnection, resource association, disconnect grace period, etc) more or less automatically.



Answered By - Bret Copeland
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to connect with a database on Access inside a intranet

 April 21, 2022     c#, connection, connection-string, database-connection, ms-access     No comments   

Issue

I have made connection with sql server but i have never done a connection with access and now this isn't in the computer local, if not it is going to be in a server users are going to full the form with their information, but the database will be in another computer, how is the connection class to be? and I have never worked in access how do i for Add, Edit, delete, and queries?

in sql server it was so easy

it was my class connection in sql and i call it since form or another class called DAO

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
namespace Proyecto1._0.Conexiones
{
    class Conexion
    {
        public SqlConnection conectar()
        {
            return new SqlConnection(@"data source=.; integrated security=true; initial catalog=dbmeridajoven;");
        }

        public bool ejecutarConsulta(string consulta)
        {
            try
            {
                SqlCommand comando = new SqlCommand(consulta, this.conectar());
                comando.Connection.Open();
                comando.ExecuteNonQuery();
                comando.Connection.Close();
                return true;
            }
            catch
            {
                MessageBox.Show("Consulta mal formada");
                return false;
            }
        }

        public DataTable regresarTabla(string consulta)
        {
            try
            {
                SqlDataAdapter adapter = new SqlDataAdapter(consulta, this.conectar());
                DataTable tabla = new DataTable("consulta");
                adapter.Fill(tabla);
                return tabla;
            }
            catch
            {
                MessageBox.Show("Consulta mal formada ");
                return new DataTable();
            }
        }
    }
}

I repeat now is with access and it is for intranet (in another computer is the server)


Solution

ConnectionStrings.com is a great resource for figuring out how to create a connection string for a variety of database engines. Here's one example of an Access connection string:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=;

Once you generate a connection string, you'll notice that the file path is included in the string; to share the database among mulitple clients, you'll need to put the database file on a network share or drive. For example, your file path could be something like "\\dbserver\databases\mydb.mdb."



Answered By - Jacob
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to connect two databases at the same time in SQL Server?

 April 21, 2022     connection, database, sql-server     No comments   

Issue

How to connect to two databases at the same time in SQL Server? i want to create a query from a local database db1 on some tables exist in an outside database db2. Im working with SQL Server.


Solution

The servers will need to be connected as a Linked Server in Server Objects, Linked Servers with a user that has access to both servers.



Answered By - DrHouseofSQL
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to replace default hikari cp to tomcat pool on spring boot 2.0

 April 21, 2022     connection, default, pool, spring-boot, tomcat     No comments   

Issue

I have migrated spring boot application to 2.0 and found out some problems with hikari connection pool. When I am fetching database data this results to hikari cp timeout ie. connection is not available. I don't know why when in the previous version this worked correctly.

Therefore I tried to use tomcat pool with this config in application.yml but it did not work (in correct YAML formatting).

spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource

My pom.xml has these dependencies related to DB things:

spring-boot-jpa
spring-boot-jdbc
jdbc7

How to exclude hikari and use tomcat connection pool?


Solution

I have found out the solution. This can be resolved in pom.xml by modifying like that:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
</dependency>

However the hikari problem was probably with default small size of connection pool. So this problem could be resolved also with this change but not verified by myself. Just note for others. Something like that:

spring.datasource.hikari.connection-timeout=60000
spring.datasource.hikari.maximum-pool-size=5


Answered By - Luke
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I open the search results in a different html page using php

 April 21, 2022     connection, html, json, php     No comments   

Issue

I have created a small search bar which will generate movie details but I want the results to open in a separate html page can you guys please help me this problem?

My code is below

<div class="form-container">

        <form method="POST">
            <div class="search-container">
                <input type="text" name="search" placeholder="Search...">
                <button class="btn btn-primary" type="submit" name="submit-search">Search</button>
            </div>
        </form> 
        <div class="resutls">
        <?php

            if (isset($_POST['submit-search'])) {

                $txtresult = $_POST['search'];

                if ($txtresult == 'red') {
                    echo "<span class= 'red'>".$txtresult."</span><br>";
                }elseif ($txtresult == 'green') {
                    echo "<span class= 'green'>".$txtresult."</span><br>";
                }

                function    getImdbRecord($title, $ApiKey)
                    {
                        $path = "http://www.omdbapi.com/?t=$title&apikey=$ApiKey";
                        $json = file_get_contents($path);
                        return json_decode($json, TRUE);

                    }
                $data = getImdbRecord($txtresult, "f3d054e8");  
                echo "<span class = 'info-box'><h3> Name :".$data['Title']."</h3><h3> Year : ".$data['Year']."</h3><h3> Duration : ".$data['Runtime'],"</h3></span>";

    }

        ?>
    </div>

Solution

You need to use the action parameter in form tag to specify a different HTML/PHP Page.

<form action="otherFile.php" method="POST">

Then you need to move the code to fetch results to otherFile.php



Answered By - ascsoftw
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to fix mysql 2003 timed out error on ubuntu server?

 April 21, 2022     connection, mysql, server     No comments   

Issue

I can't make other PC connect to my server with mysql. I already set bind-address = 0.0.0.0

netstat:

root@localhost:~# netstat -nlt | grep 3306
tcp6       0      0 :::3306                 :::*                    LISTEN

telnet:

root@localhost:~# telnet liortesta.cf 3306
Trying 104.254.244.201...
Connected to liortesta.cf.
Escape character is '^]'.
[
5.7.26-0ubuntu0.18.04.1
K)%O)Vs Z
         ^;
3mysql_native_password

nmap:

root@localhost:~# nmap -p 3306 liortesta.cf

Starting Nmap 7.60 ( https://nmap.org ) at 2019-07-25 12:39 UTC
Nmap scan report for liortesta.cf (104.254.244.201)
Host is up (0.000037s latency).
rDNS record for 104.254.244.201: linux

PORT     STATE SERVICE
3306/tcp open  mysql

Nmap done: 1 IP address (1 host up) scanned in 0.29 seconds

from another server:

nmap -p 3306 liortesta.cf

Starting Nmap 7.01 ( https://nmap.org ) at 2019-07-25 08:56 EDT
Nmap scan report for liortesta.cf (104.254.244.201)
Host is up (0.051s latency).
PORT     STATE    SERVICE
3306/tcp filtered mysql

Nmap done: 1 IP address (1 host up) scanned in 0.92 seconds
root@serv:~# telnet liortesta.cf 3306
Trying 104.254.244.201...

2003, "Can't connect to MySQL server on 'liortesta.cf' (timed out)

I don't know what to do


Solution

Sorry, server provider also has firewall and it blocked my connections



Answered By - Apepenkov
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you measure the number of open database connections

 April 21, 2022     asp.net, connection, database, sql     No comments   

Issue

I am trying to determine if I have a database connection leak. So I need to see the number of open connections. I have some simple test code that creates a leak:

protected void Page_Load(object sender, EventArgs e)
{
  for(int i = 0; i < 100; i++)
  {
    SqlConnection sql = new SqlConnection(@"Data Source=.\SQLExpress;UID=sa;PWD=fjg^%kls;Initial Catalog=ABC");
    sql.Open();
  }

}

Note there is no .Close and this does infact crash after being run 3 times in quick succession.

In order to measure the leak I am running the Performance monitor and measuring SQLServer: General Statistics/User Connections:

alt text
(source: yart.com.au)

However, these seem to be zero when I run my code:

alt text
(source: yart.com.au)

What should I change to actually see the connections?

ANSWER

I have approved an answer below. Even though it doesn't use the performance tools, its good enough for my use. Bottom line is I wanted to see how many connections remain open after opening a web page and this did the trick.


Solution

You can try running a query against the master db like this:

SELECT SPID,
       STATUS,
       PROGRAM_NAME,
       LOGINAME=RTRIM(LOGINAME),
       HOSTNAME,
       CMD
FROM  MASTER.DBO.SYSPROCESSES
WHERE DB_NAME(DBID) = 'TEST' AND DBID != 0 

See this link for more details.



Answered By - brendan
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why node.js always says I'm connected to my MongoDB even if the "URI" is fake or wrong?

 April 21, 2022     connection, mongodb, mongoose, node.js     No comments   

Issue

I'm testing mongoDB connection in node.js with mongoose. I follow the official guide of mongoose and when I try to connect like they said, mongoose always says I'm connected even if the URI given is fake or wrong. Is my connection trying correct ?

I want to connect my app to a database called 'technicaltest'.

My code:

const mongoose = require('mongoose');

const db = mongoose.createConnection('mongodb://localhost/technicaltest', {useNewUrlParser: true});

db.on('connected', () => {
    console.log('Connected to mongoDB !');
});

db.on('disconnected', () => {
    console.log('Disconnected to mongoDB !');
});

The console ouput:

> set PORT=3001 && node bin/www

Connected to mongoDB !

Same output for this code:

const mongoose = require('mongoose');

const db = mongoose.createConnection('mongodb://localhost/someWeirdyThingsHere', {useNewUrlParser: true});

db.on('connected', () => {
    console.log('Connected to mongoDB !');
});

db.on('disconnected', () => {
    console.log('Disconnected to mongoDB !');
});

I think if mongoose cannot connect to the right database in mongoDB nothing will be prompted in the console... But here... The 'connected' event is call anyway.


Solution

I think you forgot to add the port(27017) to your mongodb connection. It should be

const db = mongoose.createConnection('mongodb://localhost:27017/technicaltest', {useNewUrlParser: true});


Answered By - Spidy
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to connect to mssql using pdo through PHP and Linux?

 April 21, 2022     connection, database, pdo, php, sql-server     No comments   

Issue

I'm trying to for a new PDO connection using the following code.

new PDO("mssql:driver=????;Server={$serverName};Database={$databaseName}", $username, $password, array(PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

I'm not sure what drivers to use? Or how to install them. I can connect perfectly fine using the mssql_connect function in PHP but I want to use the PDO library instead.

My php.ini settings for mssql are:

ssql

MSSQL Support   enabled
Active Persistent Links     0
Active Links    1
Library version     FreeTDS

Directive   Local Value Master Value
mssql.allow_persistent  On  On
mssql.batchsize 0   0
mssql.charset   no value    no value
mssql.compatability_mode    Off Off
mssql.connect_timeout   5   5
mssql.datetimeconvert   On  On
mssql.max_links Unlimited   Unlimited
mssql.max_persistent    Unlimited   Unlimited
mssql.max_procs Unlimited   Unlimited
mssql.min_error_severity    10  10
mssql.min_message_severity  10  10
mssql.secure_connection Off Off
mssql.textlimit Server default  Server default
mssql.textsize  Server default  Server default
mssql.timeout   60  60

Solution

The PDO mssql driver is no more, use sqlsrv (under php windows) or dblib (under php linux)

http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx

http://www.php.net/manual/en/ref.pdo-dblib.php



Answered By - James
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What to do to make the HSQL driver working?

 April 21, 2022     connection, database, driver, hsqldb, java     No comments   

Issue

I'm currently learning some database tricks in Java and I found this nice book I'm reading. At some point, it encourages me to try a manual database connection with the following class:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DemoSelect {

    public static void main(final String[] arguments) {

        // Connection parameters
        String usr = "sa";
        String pwd = "";
        String driver = "org.hsqldb.jdbcDriver";
        String url = "jdbc:hsqldb:hsql://localhost/xdb";

        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;

        try {
            // Starting up the driver
            Class.forName(driver);

            // Connecting
            con = DriverManager.getConnection(url, usr, pwd);

            // Writing a query
            String sql = "SELECT empno, ename, hiredate, deptno FROM emp";

            // Setting up the SQL statement
            pstm = con.prepareStatement(sql);

            // Execute the SQL query
            rs = pstm.executeQuery();

            // Iterating the results
            while (rs.next()) {

                // Simple method to show the data
                System.out.print(rs.getInt("empno") + ", ");
                System.out.print(rs.getString("ename") +  ", ");
                System.out.print(rs.getDate("hiredate") + ", ");
                System.out.println(rs.getInt("deptno"));
            }
        } catch(final Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);

        } finally {
            try {

                // Closing all the opened resources
                if (rs != null) rs.close();
                if (pstm != null) pstm.close();
                if (con != null) con.close();
            } catch(final Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}

But when I try to run it, it generates an error with the following description:

java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at cap3.jdbc.DemoSelect.main(DemoSelect.java:25)
Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException:      org.hsqldb.jdbcDriver
        at cap3.jdbc.DemoSelect.main(DemoSelect.java:53)
    Caused by: java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at cap3.jdbc.DemoSelect.main(DemoSelect.java:25)
 Java Result: 1
 BUILD SUCCESSFUL(total time: 0 seconds)`

What could I be missing?

I'm using NetBeans and I downloaded the HSQL Driver. I managed to import the .jar file to the libraries and I got the following error code:

java.sql.SQLTransientConnectionException: java.net.ConnectException: Connection refused: connect
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at cap3.jdbc.DemoSelect.main(DemoSelect.java:28)
Caused by: org.hsqldb.HsqlException: java.net.ConnectException: Connection refused: connect
at org.hsqldb.ClientConnection.openConnection(Unknown Source)
at org.hsqldb.ClientConnection.initConnection(Unknown Source)
at org.hsqldb.ClientConnection.<init>(Unknown Source)
... 6 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at org.hsqldb.server.HsqlSocketFactory.createSocket(Unknown Source)
... 9 more
Exception in thread "main" java.lang.RuntimeException: java.sql.SQLTransientConnectionException: java.net.ConnectException: Connection refused: connect
at cap3.jdbc.DemoSelect.main(DemoSelect.java:53)
Caused by: java.sql.SQLTransientConnectionException: java.net.ConnectException: Connection refused: connect
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at cap3.jdbc.DemoSelect.main(DemoSelect.java:28)
Caused by: org.hsqldb.HsqlException: java.net.ConnectException: Connection refused: connect
at org.hsqldb.ClientConnection.openConnection(Unknown Source)
at org.hsqldb.ClientConnection.initConnection(Unknown Source)
at org.hsqldb.ClientConnection.<init>(Unknown Source)
... 6 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at org.hsqldb.server.HsqlSocketFactory.createSocket(Unknown Source)
... 9 more
Java Result: 1
BUILD SUCCESSFUL(total time: 1 second)

Solution

The HSQL driver is not in your classpath. You'll have to somehow include that driver jar file to it by running your program with java -cp .;hsqldb.jar DemoSelect. Use ':' as a separator instead of ';', if you're on *nix.

See also the documentation.



Answered By - nos
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to make a connection to an existing Redshift database using JDBC driver and Boto3 API in Python

 April 21, 2022     amazon-redshift, boto3, connection, jdbc, python     No comments   

Issue

I do not know how to write a connection string in Python using Boto3 API to make a jdbc connection to an existing database on AWS Redshift. I am using MobaXterm or putty to make a SSH connection. I have some codes to create the table, but am lost as to how to connect to the Database in Redshift

import boto3

s3client = boto3.client('redshift', config=client-config)

CREATE TABLE pheaapoc_schema.green_201601_csv (
    vendorid varchar(4),
    pickup_ddatetime TIMESTAMP,
    dropoff_datetime TIMESTAMP,

I need to connect to database "dummy" and create a table.


Solution

TL;DR; You do not need IAM credentials or boto3 to connect to Redshift. What you need is end_point for the Redshift cluster and redshift credentials and a postgres client using which you can connect.

You can connect to Redshift cluster just the way you connect to any Database (Like MySQL, PostgreSQL or MongoDB). To connect to any database, you need 5 items.

  1. host - (This is nothing but the end point you get from AWS console/Redshift)
  2. username - (Refer again to AWS console/Redshift. Take a look at master username section)
  3. password - (If you created the Redshift, you should know the password for master user)
  4. port number - (5439 for Redshift)
  5. Database - (The default database you created at first)

Refer to the screenshot if it is not intuitive.

What boto3 APIs do?

Boto3 provides APIs using which you can modify your Redshift cluster. For example, it provides APIs to delete your cluster, resize your cluster or take a snapshot of your cluster. They do not involve connection whatsoever.

Screenshots for reference:

End point

AWS console



Answered By - nightgaunt
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check http(s) request connection status?

 April 21, 2022     client-server, connection, http, https     No comments   

Issue

Story: In a client-server system I use a long time connection(an http(s) request from client to server with a long time timeout) in order to use notify client to do some actions(Most of data transfer is from client to server but some commands send to client in response of this http(s) request).

Problem: If client cancel the connection server can understand that but if internet connection of client loses(e.g, unplug the LAN cable or it loses the WLAN/GPRS antenna) neither client nor server understand this. Connection still remains until (some time spends and) somebody writes something in it which is too late.


PS: 0) I googled with AKC/NACK, Keep-alive, ping-pong and heartbeat key words for http(s) request and could not find a protocol which it periodically check the status of request.

1) In this you can find an argument for curl command which sets a time interval to send a props(also I monitored this with wireshark). But if still if you unplug the cable neither curl command nor server can understand the connection lost.

curl -k --keepalive-time 5 https://exampel.com/v1/v/f9a64e73/notification

2) Also here explains that there is an http header which is used to use a connection multiple time.


Solution

In server side and with nginx web-server we can enable TCP keep-alive probe with so_keepalive=on as listen input argument. Find more information in this link.



Answered By - Bonje Fir
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is connecting to SQL Server very slow?

 April 21, 2022     c#, connection, sql-server     No comments   

Issue

We see that creating new connections takes about 250 milliseconds, which is much slower than expected.

From our application server to the SQL Server, we have about 1 millisecond ping-time, and we are operating inside pretty fast LAN.

Our connection string is:

Data Source=SQLServer;Initial Catalog=Database;Integrated Security=True

I have measured elapsed time around this simple statement

var conn = new SqlConnection(_connectionString);

if (conn.State == ConnectionState.Closed)
{
    var sw = Stopwatch.StartNew();
    await conn.OpenAsync().ConfigureAwait(false);
    sw.StopAndLogIfDelay(20, _log, "Open SQL Server connection");
}

I would not expect 250 milliseconds to connect in a fast LAN. Does anyone have ideas or experience in where the problem could be?


Solution

Setting minimum connections to 50 in th sql-server connection pool solved the immidate problem.

What remains is to investigate why open db-connections takes such a long time in our organisation. I will ally with our network-team to see if we can locate the problem.



Answered By - Torben Nielsen
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I make my Java application identify itself to Oracle on connection?

 April 21, 2022     connection, java, oracle, properties     No comments   

Issue

When my application connects to an Oracle database I want to be able to see by looking at the active sessions in the database that it is connected. Currently it identifies itself as "JDBC Thin Client" because that's the driver that I'm using, but other Java based applications that I have are somehow able to set this value to something more meaningful, like "SQL Developer". I thought it was a property of the Connection or the OracleDataSource, but I've not managed to find one that does the trick. Is this possible? In case it matters, I'm using Java 1.5, with Oracle 10g and the 10g thin driver.


Solution

java.util.Properties props = new java.util.Properties();
props.setProperty("password","mypassword");
props.setProperty("user","myusername");
props.put("v$session.osuser", System.getProperty("user.name").toString());
props.put("v$session.machine", InetAddress.getLocalHost().getCanonicalHostName());
props.put("v$session.program", "My Program Name");
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
Connection conn=
    DriverManager.getConnection("jdbc:oracle:thin:@myhostname:1521:mysid", props);

SQL>select username,osuser,program,machine
from v$session
where username = 'ROB'; 

USERNAME  OSUSER       PROGRAM             MACHINE
--------- -----------  ------------------  -----------
ROB       rmerkw       My Program Name     machine

At application level you can use the following methods to set client_info, module and action in v$session:

dbms_application_info.set_client_info
dbms_application_info.set_module
dbms_application_info.set_action


Answered By - Rob van Laarhoven
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make in alertDialog by clicking OK then, go to the next page?

 April 21, 2022     android, android-studio, connection, java     No comments   

Issue

My problems :

1. I have error on it.

2. Why cannot go to the next page when I use startActivity?

3. How to solve?

4. I already use startActivity by using Intent method

Below is prove 1 :

enter image description here

Below is prove 2 :

enter image description here

Below is prove 3 :

enter image description here

Below is code snippet :

 public void OnLog(View view)
 {
    String Username = username.getText().toString();
    String Password = password.getText().toString();
    String type = "login";

    if(Username.equals("") || Password.equals(""))
    {
        Toast.makeText(getApplicationContext(), "Please fill the Username and Password!", Toast.LENGTH_LONG).show();
    }
    else {

        Background bg = new Background(Context, act);
        bg.execute(type, Username, Password);
    }
}

enter image description here

Below is coding for Background.java :

public class Background extends AsyncTask<String,Void,String> {

Context context;
AlertDialog alertDialog;

Background(Context ctx) {
    context = ctx;
}

@Override
protected String doInBackground(String... params)
{
    String type = params[0];
    String login_url = "http://172.20.10.4/LoginLab3.php";
    String reg_url = "http://172.20.10.4/RegisterLab3.php";
    if (type.equals("login")) {
        try {
            String username = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
                    + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));
            String result = "";
            String line = "";
            while ((line = bufferedReader.readLine()) != null)
            {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    else if(type.equals("register"))
    {
        try {
            String name = params[1];
            String surname = params[2];
            String age = params[3];
            String username = params[4];
            String password = params[5];
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
                    +URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
                    +URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
                    +URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
                    +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null)
            {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute()
{
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result)
{
    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setTitle("Login Status");
    dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            startActivity(new Intent(Login.this, Welcome.class));
        }
    });
    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
    dialog.create().show();
}

@Override
protected void onProgressUpdate(Void... values)
{
    super.onProgressUpdate(values);
}
}

Help me! i have some problem on it. I already use almost all method, but cannot go to the next page. Why ?


Solution

Activity OnCreate Code

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Pass activity to Async Task
    new Background(this).execute();
 }  

Async Task

public class Background extends AsyncTask<Void,Void,Void> {
    private Context context;

    public Background(Context context){
        this.context=context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Intent intent = new Intent(context, TargetActivity.class);
        context.startActivity(intent);
        ((Activity)context).finish();
    }
}


Answered By - Aravinth Velusamy
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to instance 1 connection class for multiple requests?

 April 21, 2022     connection, database, gradle, java, postgresql     No comments   

Issue

So I'm currently working on a project that will be using a database but its my first time trying fiddling with it on java. But I'm already seeing my first problem is how would i make one single file that handles connection while other files handles GET/ADD/UPDATE/DELETE (one for each table) what would properly be the best way on doing this ? To not having to place connection values in each file and do the connection

I though about extending the connection class with the other classes but idk if its a great idea.

import java.sql.*;

public class DatabaseConnection {

    public static void main(String[] args) {
        final String url = "jdbc:postgresql://localhost:5432/Database";
        final String user = "dbuser";
        final String password = "dbpass";

        try(Connection conn = DriverManager.getConnection(url, user, password)) {
            System.out.println("Connection successful!");
        } catch (SQLException e) {
            System.out.println("Connection failure.");
            e.printStackTrace();
        }
    }
}

What would be the best approach?


Solution

Maybe i'm wrong, but i think you need connection pool. Try to find instruction here https://www.baeldung.com/java-connection-pooling



Answered By - Serhii Marynenko
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to connect ports to a Bus properly in VHDL?

 April 21, 2022     bus, connection, port, vhdl     No comments   

Issue

i am currently fooling around with some VHDL Code to try out a view things. For my current approach i need to split up a bus into ports. Therefore it would be the prettiest solution to "hard connect" the bus with the ports in the entity declaration. Is this possible?

Or is the only solution to connect them in the architecture and "write" them into each other in there?

This is the snippet i am trying to implement accordingly.

entity test is
  port (
    bus    : out std_ulogic_vector(3 downto 0);
    port3   : out std_ulogic;
    port2   : out std_ulogic;
    port1   : out std_ulogic;
    port0   : out std_ulogic;
  );
end test;

Thank you very much for your help.


Solution

The entity describes the external connectivity. The Architecture describes its internal behaviour. So "hardwiring" in the entity is not possible.

In your example, you would need to connect the ports to the same connects as the "bus" output

Note: bus is a reserved word in VHDL.



Answered By - Tricky
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing