Automating connection string to mysql?
I've just started to venture into some of my own php scripts that don't not follow the step by step beginner tutorials. What I can't seem to understand though is how do you get dreamweaver to automatically write the script to establish a database connection. I've connected to the database by going to DataBase -> Connect and inputting the settings in the dialogue box. DW acknowleges that the connection exists. But it doesn't automatically write the code to facilitate the connection, ie
$hostname_conntest = "my_hostname";
$database_conntest = "my_db";
$username_conntest = "my_username";
$password_conntest = "my_password"; etc..
I have to first create a record set to get this connection code written and then it seems to include about 25 more lines of code that don't seem necessary for what I'm trying to do, such as inserting magicquotes formula and so on.
does anyone know a simple one button solution to get the very basic connection settings to write to the source code of a new php doc.?
Thank you.
I usually just put the connection details in a stand alone file and use an include file in each page which needs a database connection
<?php include('database_connection.php'); ?>
Similar Messages
-
Report Designer odbc connection string for data source using a parameter
I am using stand alone report designer 3 for the present and have a question/problem regarding the odbc connection string for MySQL when setting up the data-source
I need to be able to enter a parameter which is the database name i.e. BOE-201401 or say BOE-201312 etc from a list of databases the user can choose from.
at present the odbc connection string points to BOE-201402
the connection string is at present Dsn=Development Server for MYsql;description=MYSQL;server=ldndw01;database=BOE-201402;port=3306
my parameter has the name BOE_DATABASE
and in an expression it is as such
=Parameters!BOE_DATABASE.Value
I want to point the datasource for the report to the parameter value before the user sees the report.Hi Leslie,
Based on your description, we want to design a report with a dynamic DataSource connection string. There are the basic steps below for your reference:
Create report with static database.
Change data source to report parameter.
Send new database connection string as a report parameter.
More detail information, please refer to the following blog: Dynamic Database in SSRS 2008.
http://haseebmukhtar.wordpress.com/2011/11/09/dynamic-database-in-ssrs-2008/
Regards,
Alisa Tang
Alisa Tang
TechNet Community Support -
Help with mySQL Connection string
Here is hoping someone can help & once I get it down I promise I'll post all my work on this list so some other newbie can benefit.
I'm simply trying to run a very very straightforward JDBC test with mySQL & I keep getting the "Server configuration denies access to data source" error. But before you tell me that I must simply look at what my mysql.db & mysql.user table allows - I'VE TRIED THAT. I realize that the error is probably there somewhere - but I can't see it.
I've tried connecting with 2 different accounts - the provided "root" & a user I created "deep" to 2 different databases the provided "test" & "testdb" which I created) . Here is what mysql says about the two different databases
mysql> select * from db;
Host | Db | User |.......
-----+------------+-------
| % | test | | ......
| % | test\_% | | ........
| localhost | testdb | deep |........Note that "root" should have access to "test" & deep@localhost should have access to "testdb" right?
So here are all the connection strings I have tried - all return the same error below
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "mypass"
// "jdbc:mysql://localhost:3306/testdb", "deep", "mypass"
// "jdbc:mysql://localhost/testdb?user=deep&password=mypass"
// "jdbc:mysql://localhost/testdb", "deep", "mypass"
// "jdbc:mysql://localhost:3306/testdb?user=deep@localhost&password=mypass"
// "jdbc:mysql://localhost:3306/testdb?user=deep&password=mypass"
// "jdbc:mysql://localhost/testdb", "deep@localhost", "mypass"
// "jdbc:mysql:///test", "root", "mypass"
// "jdbc:mysql://localhost/test", "root@localhost", "mypass"
);My Error:
Exception in thread "main" java.sql.SQLException: Server configuration denies access to data source
at org.gjt.mm.mysql.MysqlIO.init(MysqlIO.java:193)
at org.gjt.mm.mysql.Connection.connectionInit(Connection.java:261)
at org.gjt.mm.mysql.jdbc2.Connection.connectionInit(Connection.java:89)
at org.gjt.mm.mysql.Driver.connect(Driver.java:167)
at java.sql.DriverManager.getConnection(DriverManager.java:517)
at java.sql.DriverManager.getConnection(DriverManager.java:199)
at TestMySQL4.main(TestMySQL4.java:76)BTW:
I am using MacOSX 10.1
MySQL 3.23.42
The driver is: mm.mysql-2.0.6.jar
Please help!
'deephi amandeep
well i m getting the same error message when trying to connect MYSQL using mm.jdbc driver.
java.sql.SQLException : Server configuration denies access to data base source.
query.jdbcDriver org.gjt.mm.mysql.Driver
query.databaseURL jdbc:mysql://aaa.bbb.com/pluto
query.databaseUserName samin
query.databasePwd samin
query.summaries true
i hve installed mysql on server aaa.bbb.com network 1
and trying to run application on network 2
Thanks
samir -
Has anyone run the connection pooling for mysql & tomcat successfully?
I'm trying to set up connection pooling. I'm following the how-to page at
http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jndi-datasource-examples-howto.html
But when i test the DBTest/test.jsp file, tomcat displays an error =
could not load jdbc driver class 'null'(msdos)
i have placed all the required .jar files in the tomcat lib.
below is the cofiguration i did to the server.xml file
<!-- Example Server Configuration File -->
<!-- Note that component elements are nested corresponding to their
parent-child relationships with each other -->
<!-- A "Server" is a singleton element that represents the entire JVM,
which may contain one or more "Service" instances. The Server
listens for a shutdown command on the indicated port.
Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" or "Loggers" at this level.
-->
<Server port="8005" shutdown="SHUTDOWN" debug="0">
<!-- Uncomment these entries to enable JMX MBeans support -->
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"
debug="0"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
debug="0"/>
<!-- Global JNDI resources -->
<GlobalNamingResources>
<!-- Test entry for demonstration purposes -->
<Environment name="simpleValue" type="java.lang.Integer" value="30"/>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users -->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved">
</Resource>
<ResourceParams name="UserDatabase">
<parameter>
<name>factory</name>
<value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
</parameter>
<parameter>
<name>pathname</name>
<value>conf/tomcat-users.xml</value>
</parameter>
</ResourceParams>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" (and therefore the web applications visible
within that Container). Normally, that Container is an "Engine",
but this is not required.
Note: A "Service" is not itself a "Container", so you may not
define subcomponents such as "Valves" or "Loggers" at this level.
-->
<!-- Define the Tomcat Stand-Alone Service -->
<Service name="Tomcat-Standalone">
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Each Connector passes requests on to the
associated "Container" (normally an Engine) for processing.
By default, a non-SSL HTTP/1.1 Connector is established on port 8080.
You can also enable an SSL HTTP/1.1 Connector on port 8443 by
following the instructions below and uncommenting the second Connector
entry. SSL support requires the following steps (see the SSL Config
HOWTO in the Tomcat 4.0 documentation bundle for more detailed
instructions):
* Download and install JSSE 1.0.2 or later, and put the JAR files
into "$JAVA_HOME/jre/lib/ext".
* Execute:
%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA (Windows)
$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA (Unix)
with a password value of "changeit" for both the certificate and
the keystore itself.
By default, DNS lookups are enabled when a web application calls
request.getRemoteHost(). This can have an adverse impact on
performance, so you can disable it by setting the
"enableLookups" attribute to "false". When DNS lookups are disabled,
request.getRemoteHost() will return the String version of the
IP address of the remote client.
-->
<!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8081 -->
<Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
port="8080" minProcessors="5" maxProcessors="75"
enableLookups="true" redirectPort="8443"
acceptCount="100" debug="0" connectionTimeout="20000"
useURIValidationHack="false" disableUploadTimeout="true" />
<!-- Note : To disable connection timeouts, set connectionTimeout value
to -1 -->
<!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<!--
<Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
port="8443" minProcessors="5" maxProcessors="75"
enableLookups="true"
acceptCount="100" debug="0" scheme="https" secure="true"
useURIValidationHack="false" disableUploadTimeout="true">
<Factory className="org.apache.coyote.tomcat4.CoyoteServerSocketFactory"
clientAuth="false" protocol="TLS" />
</Connector>
-->
<!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
<Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
port="8009" minProcessors="5" maxProcessors="75"
enableLookups="true" redirectPort="8443"
acceptCount="10" debug="0" connectionTimeout="20000"
useURIValidationHack="false"
protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler"/>
<!-- Define an AJP 1.3 Connector on port 8009 -->
<!--
<Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
port="8009" minProcessors="5" maxProcessors="75"
acceptCount="10" debug="0"/>
-->
<!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
<!-- See proxy documentation for more information about using this. -->
<!--
<Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
port="8082" minProcessors="5" maxProcessors="75"
enableLookups="true" disableUploadTimeout="true"
acceptCount="100" debug="0" connectionTimeout="20000"
proxyPort="80" useURIValidationHack="false" />
-->
<!-- Define a non-SSL legacy HTTP/1.1 Test Connector on port 8083 -->
<!--
<Connector className="org.apache.catalina.connector.http.HttpConnector"
port="8083" minProcessors="5" maxProcessors="75"
enableLookups="true" redirectPort="8443"
acceptCount="10" debug="0" />
-->
<!-- Define a non-SSL HTTP/1.0 Test Connector on port 8084 -->
<!--
<Connector className="org.apache.catalina.connector.http10.HttpConnector"
port="8084" minProcessors="5" maxProcessors="75"
enableLookups="true" redirectPort="8443"
acceptCount="10" debug="0" />
-->
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host). -->
<!-- Define the top level container in our container hierarchy -->
<Engine name="Standalone" defaultHost="localhost" debug="0">
<!-- The request dumper valve dumps useful debugging information about
the request headers and cookies that were received, and the response
headers and cookies that were sent, for all requests received by
this instance of Tomcat. If you care only about requests to a
particular virtual host, or a particular application, nest this
element inside the corresponding <Host> or <Context> entry instead.
For a similar mechanism that is portable to all Servlet 2.3
containers, check out the "RequestDumperFilter" Filter in the
example application (the source for this filter may be found in
"$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
Request dumping is disabled by default. Uncomment the following
element to enable it. -->
<!--
<Valve className="org.apache.catalina.valves.RequestDumperValve"/>
-->
<!-- Global logger unless overridden at lower levels -->
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="catalina_log." suffix=".txt"
timestamp="true"/>
<!-- Because this Realm is here, an instance will be shared globally -->
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
debug="0" resourceName="UserDatabase"/>
<!-- Comment out the old realm but leave here for now in case we
need to go back quickly -->
<!--
<Realm className="org.apache.catalina.realm.MemoryRealm" />
-->
<!-- Replace the above Realm with one of the following to get a Realm
stored in a database and accessed via JDBC -->
<!--
<Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="org.gjt.mm.mysql.Driver"
connectionURL="jdbc:mysql://localhost/authority"
connectionName="test" connectionPassword="test"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name" />
-->
<!--
<Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
connectionName="scott" connectionPassword="tiger"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name" />
-->
<!--
<Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="sun.jdbc.odbc.JdbcOdbcDriver"
connectionURL="jdbc:odbc:CATALINA"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name" />
-->
<!-- Define the default virtual host -->
<Host name="localhost" debug="0" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Context path="/my-jsp" docBase="c:\JSP-Files" debug="0"
privileged="true" reloadable="true" />
<Context path="" docBase="c:\Inetpub\wwwroot" debug="0" privileged="true" />
<Context path="/sharon" docBase="C:\Tomcat 4.1\webapps\sharon" debug="0" privileged="true" />
<!-- Normally, users must authenticate themselves to each web app
individually. Uncomment the following entry if you would like
a user to be authenticated the first time they encounter a
resource protected by a security constraint, and then have that
user identity maintained across all web applications contained
in this virtual host. -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn"
debug="0"/>
-->
<!-- Access log processes all requests for this virtual host. By
default, log files are created in the "logs" directory relative to
$CATALINA_HOME. If you wish, you can specify a different
directory with the "directory" attribute. Specify either a relative
(to $CATALINA_HOME) or absolute path to the desired directory.
-->
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs" prefix="localhost_access_log." suffix=".txt"
pattern="common" resolveHosts="false"/>
-->
<!-- Logger shared by all Contexts related to this virtual host. By
default (when using FileLogger), log files are created in the "logs"
directory relative to $CATALINA_HOME. If you wish, you can specify
a different directory with the "directory" attribute. Specify either a
relative (to $CATALINA_HOME) or absolute path to the desired
directory.-->
<Logger className="org.apache.catalina.logger.FileLogger"
directory="logs" prefix="localhost_log." suffix=".txt"
timestamp="true"/>
<!-- Define properties for each web application. This is only needed
if you want to set non-default properties, or have web application
document roots in places other than the virtual host's appBase
directory. -->
<!-- Tomcat Root Context -->
<!--
<Context path="" docBase="ROOT" debug="0"/>
-->
<!-- Tomcat Examples Context -->
<Context path="/examples" docBase="examples" debug="0"
reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="true"/>
<Ejb name="ejb/EmplRecord" type="Entity"
home="com.wombat.empl.EmployeeRecordHome"
remote="com.wombat.empl.EmployeeRecord"/>
<!-- If you wanted the examples app to be able to edit the
user database, you would uncomment the following entry.
Of course, you would want to enable security on the
application as well, so this is not done by default!
The database object could be accessed like this:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
UserDatabase database =
(UserDatabase) envCtx.lookup("userDatabase");
-->
<!--
<ResourceLink name="userDatabase" global="UserDatabase"
type="org.apache.catalina.UserDatabase"/>
-->
<!-- PersistentManager: Uncomment the section below to test Persistent
Sessions.
saveOnRestart: If true, all active sessions will be saved
to the Store when Catalina is shutdown, regardless of
other settings. All Sessions found in the Store will be
loaded on startup. Sessions past their expiration are
ignored in both cases.
maxActiveSessions: If 0 or greater, having too many active
sessions will result in some being swapped out. minIdleSwap
limits this. -1 means unlimited sessions are allowed.
0 means sessions will almost always be swapped out after
use - this will be noticeably slow for your users.
minIdleSwap: Sessions must be idle for at least this long
(in seconds) before they will be swapped out due to
maxActiveSessions. This avoids thrashing when the site is
highly active. -1 or 0 means there is no minimum - sessions
can be swapped out at any time.
maxIdleSwap: Sessions will be swapped out if idle for this
long (in seconds). If minIdleSwap is higher, then it will
override this. This isn't exact: it is checked periodically.
-1 means sessions won't be swapped out for this reason,
although they may be swapped out for maxActiveSessions.
If set to >= 0, guarantees that all sessions found in the
Store will be loaded on startup.
maxIdleBackup: Sessions will be backed up (saved to the Store,
but left in active memory) if idle for this long (in seconds),
and all sessions found in the Store will be loaded on startup.
If set to -1 sessions will not be backed up, 0 means they
should be backed up shortly after being used.
To clear sessions from the Store, set maxActiveSessions, maxIdleSwap,
and minIdleBackup all to -1, saveOnRestart to false, then restart
Catalina.
-->
<!--
<Manager className="org.apache.catalina.session.PersistentManager"
debug="0"
saveOnRestart="true"
maxActiveSessions="-1"
minIdleSwap="-1"
maxIdleSwap="-1"
maxIdleBackup="-1">
<Store className="org.apache.catalina.session.FileStore"/>
</Manager>
-->
<Environment name="maxExemptions" type="java.lang.Integer"
value="15"/>
<Parameter name="context.param.name" value="context.param.value"
override="false"/>
<Resource name="jdbc/EmployeeAppDb" auth="SERVLET"
type="javax.sql.DataSource"/>
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/TestDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>user</name>
<value>javauser</value>
</parameter>
<parameter>
<name>password</name>
<value>javadude</value>
</parameter>
<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>org.gjt.mm.mysql.Driver</value>
</parameter>
<!-- The JDBC connection url for connecting to your MySQL dB.
The autoReconnect=true argument to the url makes sure that the
mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
connection. mysqld by default closes idle connections after 8 hours.
-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/javatest?autoReconnect=true</value>
</parameter>
</ResourceParams>
<Resource name="mail/Session" auth="Container"
type="javax.mail.Session"/>
<ResourceParams name="mail/Session">
<parameter>
<name>mail.smtp.host</name>
<value>localhost</value>
</parameter>
</ResourceParams>
<ResourceLink name="linkToGlobalResource"
global="simpleValue"
type="java.lang.Integer"/>
</Context>
</Host>
</Engine>
</Service>
<!-- The MOD_WEBAPP connector is used to connect Apache 1.3 with Tomcat 4.0
as its servlet container. Please read the README.txt file coming with
the WebApp Module distribution on how to build it.
(Or check out the "jakarta-tomcat-connectors/webapp" CVS repository)
To configure the Apache side, you must ensure that you have the
"ServerName" and "Port" directives defined in "httpd.conf". Then,
lines like these to the bottom of your "httpd.conf" file:
LoadModule webapp_module libexec/mod_webapp.so
WebAppConnection warpConnection warp localhost:8008
WebAppDeploy examples warpConnection /examples/
The next time you restart Apache (after restarting Tomcat, if needed)
the connection will be established, and all applications you make
visible via "WebAppDeploy" directives can be accessed through Apache.
-->
<!-- Define an Apache-Connector Service -->
<!--
<Service name="Tomcat-Apache">
<Connector className="org.apache.catalina.connector.warp.WarpConnector"
port="8008" minProcessors="5" maxProcessors="75"
enableLookups="true" appBase="webapps"
acceptCount="10" debug="0"/>
<Engine className="org.apache.catalina.connector.warp.WarpEngine"
name="Apache" debug="0">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="apache_log." suffix=".txt"
timestamp="true"/>
<Realm className="org.apache.catalina.realm.MemoryRealm" />
</Engine>
</Service>
-->
</Server>
Pleas4 help!!!you have your driver jar in Tomcat\common\lib?
if so, check your classpath, it could be that. -
Can' t connect Java with MySQL
My goal is to connect Java with MySQL. I found many solutions on Internet, but I always get the same mistake:
SQLException: No suitable driver
SQLState: 08001
VendorError: 0MySQL works fine alone or with php.Only thing left me to think is that the installed versions are not compatible for this mysql-connector-java-5.0.4
I don't believe that could be a reason.
Installed versions are:
Apache Tomcat 5.5.20 Server
Apache HTTP Server 2.2.4
PHP 5.2.0
MySQL 5.2
jre 1.5.0_11
jdk1.5.0_11
Apache Tomacat JK2 connector Version: 1.2.20 File Name: mod_jk-apache-2.2.3.so
mysql-connector-java-5.0.4
I also set connector in class path: C:\mysql-connector-java-5.0.4;C:\mysql-connector-java-5.0.4\mysql-connector-java-5.0.4-bin.jar;C:\mysql-connector-java-5.0.4\src\com\mysql\jdbc
For installation I used manulas from:
http://apacheguide.org/jsp.php
http://doc.51windows.net/mysql/?url=/MySQL/ch23s03.html
Here is also a test code in java:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connect
public static void main (String[] args)
Connection conn = null;
try {
conn =
DriverManager.getConnection("jdbc:mysql://localhost/first_test" +
"user=monty&password=greatsqldb");
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}i'm desperate, please help or tell me someone who'll know the answer.
Thank You in advancehey buddy .. it seems yr code is wrong .. in getconnection () method u should also specify the port ,which u r not doing ...
the default port for MySQL is 3306 ... see below i am giving you a sample code ... its working fine .. and dont forget to put the MySQL driver jar path in to classpath and also copy the jar into common/lib folder of your tomcat ....
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLConnectionTest {
public static void main(String[] args) {
new MySQLConnectionTest().connTest();
public void connTest() {
String tableName = "portfolio"; //change as per setting
String hostName = "10.81.9.39"; // please change for the target database ip or hostname
String dbPort = "3306"; //change if not using the default
String dbName = "tradingsystem"; //change as per the given DB name
String username = "root"; //change as per setting
String password = "password"; //change as per setting
System.out.println("before try");
Double data=0.0;
Double data1=0.0;
try {
Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("before driver manager");
Connection conn = DriverManager.getConnection("jdbc:mysql://"+hostName+":"+dbPort+"/"+dbName, username, password);
String query1 = "select * from "+tableName+" where User_id='trader1' and Stock_Type='Equity'";
System.out.println("quesry1="+query1);
Statement stmt = conn.createStatement();
ResultSet rs1 = stmt.executeQuery(query1);
while(rs1.next())
System.out.println("hiiiiii for rs1");
System.out.println(rs1);
Quantity=(Integer)rs1.getObject(5);
MarketPrice=(Double) rs1.getObject(8);
data=Quantity*MarketPrice;
data1+=data;
System.out.println("data1="+data1);
i=0;
rs1.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace(System.err);
} catch (SQLException e) {
e.printStackTrace(System.err);
i hope it will work for u...
cheers, -
Can't Connect to the Mysql Database using J2SE jdk1.5
Can anyone tell me why this error occurs ????????????????????
Following are the codes ;
package dbconnect2;
import java.sql.*;
public class dbconn2 {
public static final String URL =
"jdbc:mysql://localhost:3306/test";
public static final String USERNAME = "test";
public static final String PASSWORD = "password";
* @param args the command line arguments
public static void main(String[] args) throws Exception {
// TODO code application logic here
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
Statement stm = connection.createStatement();
ResultSet rs = stm.executeQuery("select * from emp");
while (rs.next())
String strnaam = rs.getString("emp_name");
System.out.println(strnaam);
finally {
if (connection != null)
connection.close();
================================================================================
This is the run time error ;
init:
deps-jar:
compile:
run:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:164)
at dbconnect2.dbconn2.main(dbconn2.java:39)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
please help me to sort this out
Thanks
SishaniI've solved the DW problem by changing the site folders from
'db' to 'wwwroot' e.g. 'C:\CFusionMX\db\' is now
'C:\CFusionMX\wwwroot\
However I'm now back to my original problem. I've lost my
mqysql connection in CF Adminstrator. Before I made these changes I
could connect to my mysql databases using the following settings:
JDBC URL: jdbc:mysql://localhost:3306/test
Driver Name: MySQL Connector J
using the following Java path and file:
C:\CFusionMX\wwwroot\WEB-INF\lib\mysql-connector-java-3.0.17-ga-bin.jar
Now these settings give me the following error:
"Connection verification failed for data source: javaserver
[]java.sql.SQLException: SQLException occurred in JDBCPool
while attempting to connect, please check your username, password,
URL, and other connectivity info.
The root cause was that: java.sql.SQLException: SQLException
occurred in JDBCPool while attempting to connect, please check your
username, password, URL, and other connectivity info"
Any suggestions on this would also be welcome.
Thanks again to everyone for their help.
Sincerely,
Graham A. Kerby -
How do I connect to a mysql database?
I am trying to write a small program with Java to do some operation on a Mysql database. The first step is to connect to the database. Can anybody give me some information about how to connect to it with JDBC? Thank you in advance!
// SQL jdbc driver
String SQLDriver = "com.mysql.jdbc.Driver";
// SQL connection string
String SQLConnectionString = "jdbc:mysql://localhost/passport?user=root&password=your_MYSQL_Password";
// Load database driver
Class.forName(connectionDriver);
// Make connection
Connection sqlconn = DriverManager.getConnection(connectionString);rykk -
Problem with Connect C# to MySQL
I have problem Connect C# to MySQL
When I Debug and Click Button < MySqlException was unhandled> "Unable to connect to any of the specified MySQL hosts."
In > View Detail " {"Unable to connect to any of the specified MySQL hosts."} "
private void button1_Click(object sender, EventArgs e)
string MyConString = "SERVER=localhost;" + "DATABASE=mysql;" + "UID=root;" + "PASSWORD=......;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from Test";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
string thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
thisrow += Reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
connection.Close();
Can someone help me ?I have problem Connect C# to MySQL
When I Debug and Click Button < MySqlException was unhandled> "Unable to connect to any of the specified MySQL hosts."
In > View Detail " {"Unable to connect to any of the specified MySQL hosts."} "
private void button1_Click(object sender, EventArgs e)
string MyConString = "SERVER=localhost;" + "DATABASE=msql;" + "UID=root;" + "PASSWORD=......;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from Test";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
string thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
thisrow += Reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
connection.Close();
Can someone help me ?
Hello Shamugia,
it's a good resource for connection string
http://www.connectionstrings.com/mysql
Bye
Carmelo La Monica
http://community.visual-basic.it/carmelolamonica/ -
The connection string for coded UI Data driven test using excel data source is not working
Hello,
I am using the visual studio 2012 coded UI test, i added the following connection strings to connect to an excel data source:
[DataSource("System.Data.Odbc", "Dsn=Excel Files;Driver={Microsoft Excel Driver (*.xls)};dbq=C:\\Users\\shaza.said.ITWORX\\Desktop\\Automation\\On-track Automation Framework\\On-track_Automation\\Automation data file.xls;defaultdir=.;driverid=790;maxbuffersize=2048;pagetimeout=5;readonly=true",
"Sheet1$", DataAccessMethod.Sequential), TestMethod]
[DataSource("System.Data.Odbc", "Dsn=Excel Files;dbq=|DataDirectory|\\Automation data file.xls;defaultdir=C:\\Users\\shaza.said.ITWORX\\Desktop\\Automation\\On-track Automation Framework\\On-track_Automation\\Automation data file.xls;driverid=1046;maxbuffersize=2048;pagetimeout=5",
"Sheet1$", DataAccessMethod.Sequential), TestMethod]
But i get the following error:
"The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library.
Error details: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Thanks,
ShazaThanks for Adrian's help.
Hi shaza,
From the error message, I suggest you can refer the Adrian's suggestion to check the date source connection string correctly.
In addition, you can refer the following about how to Create a Data-Driven Coded UI Test to check your issue:
http://msdn.microsoft.com/en-us/library/ee624082.aspx
Or you can also try to use a Configuration File to Define a Data Source for coded UI test.
For example:
<?xml
version="1.0"
encoding="utf-8"
?>
<configuration>
<configSections>
<section
name="microsoft.visualstudio.testtools"
type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection,
Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<connectionStrings>
<add
name="ExcelConn"
connectionString="Dsn=Excel Files;dbq=E:\Unit Test\AddClass\AddUnitTest\add.xlsx;defaultdir=.;
driverid=790; maxbuffersize=2048; pagetimeout=60;"
providerName="System.Data.Odbc"/>
<add
name="ExcelConn1"
connectionString="Dsn=Excel Files;dbq=E:\Unit Test\AddClass\AddUnitTest\sum.xlsx;defaultdir=.;
driverid=790;maxbuffersize=2048;pagetimeout=60"
providerName="System.Data.Odbc"/>
</connectionStrings>
<microsoft.visualstudio.testtools>
<dataSources>
<add
name="ExcelDS_Addition"
connectionString="ExcelConn"
dataTableName="Addition$"
dataAccessMethod="Sequential"/>
<add
name="ExcelDS_Multiply"
connectionString="ExcelConn1"
dataTableName="Multiply$"
dataAccessMethod="Sequential"/>
</dataSources>
</microsoft.visualstudio.testtools>
</configuration>
For more information, please see:https://msdn.microsoft.com/en-us/library/ms243192.aspx
Best Regards,
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Cannot connect java to mysql server 2000
I was unable to connect to the mysql server 2000 with the jcreator.
The following exception was thrown:
java.net.SocketException
MESSAGE: java.net.ConnectException: Connection refused: connect
STACKTRACE:
java.net.SocketException: java.net.ConnectException: Connection refused: connect at com.mysql.jdbs.StandardSocketFactory.connect<StandardSocketFactory.java:156?
at com.mysql.jdbc.MysqlIO.<init><MysqlIO.java:284>
** END NESTED EXCEPTION **
and the code i used was :
package com.stardeveloper.example;
import java.sql.*;
public class JCustomer {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///Customer", "user", " ");
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
I donot have any user and pwd for the MYsql server, it is local host connection and window authentication is used.eventhough it is local ,you may need to specify dns/localhost/ip with port number.
otherwise you can use myODBC driver which is freely available in mysql website. you can connect to the database using Data source Name, just like using any other ODBC connectivity. -
Connect JBOSS to MySQL using datasource,both servers are on different machi
HI,
In my application, I use JBOSS server and MySQL database.JBOSS and MySQL server are on two different machines.I am using mysql datasource,not driver manager to get the connection. i configured mysql-ds.xml and put it in %JBOSS_HOME%\server\default\deploy directory.
I have also put the mysql connector jar in the %JBOSS_HOME%\server\default\lib directory.
mysql-ds.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: mysql-ds.xml 41016 2006-02-07 14:23:00Z acoliver $ -->
<!-- Datasource config for MySQL using 3.0.9 available from:
http://www.mysql.com/downloads/api-jdbc-stable.html
-->
<datasources>
<local-tx-datasource>
<jndi-name>JBossAtWorkDS</jndi-name>
<connection-url>jdbc:mysql://192.168.1.3:3306/JBossAtWorkDS</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>sa</user-name>
<password></password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
<!-- should only be used on drivers after 3.22.1 with "ping" support
<valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
-->
<!-- sql to call when connection is created
<new-connection-sql>some arbitrary sql</new-connection-sql>
-->
<!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
-->
<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
code to make the connection is as follows...
public class JDBCCarDAO implements CarDAO
private List carList;
private static final String DATA_SOURCE="java:comp/env/jdbc/JBossAtWorkDS";
public JDBCCarDAO()
public List findAll()
List carList = new ArrayList();
DataSource dataSource = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
dataSource = ServiceLocator.getDataSource(DATA_SOURCE);
conn = dataSource.getConnection();
stmt = conn.createStatement();
stmt.execute("select * from CAR");
rs = stmt.getResultSet();
while(rs.next())
CarDTO car = new CarDTO();
car.setMake(rs.getString("MAKE"));
car.setModel(rs.getString("MODEL"));
car.setModelYear(rs.getString("MODEL_YEAR"));
carList.add(car);
catch (Exception e)
System.out.println("No SQL connection is made"+e);
finally
try
if(rs != null){rs.close();}
if(stmt != null){stmt.close();}
if(conn != null){conn.close();}
catch(Exception e)
System.out.println(e);
return carList;
I am getting an error as follows...
No SQL connection is made.
org.Jboss.util.NestedSQLException:Could not create connection; -nested throwable: (java.sql.SQLException:Unable to connect to any host due to exception:java.net.ConnectException:Connection Time out:connect......
how to get rid of this problem????plz...someone help me....If you have access to a copy of TimesTen 6.0 you can look in the AppServer Configuration Guide (appsrv.pdf) that was shipped with that release. This guide is currently being rewritten and so is not yet available for 7.0.
If you can't get hold of a copy, e-mail me at [email protected] and I'll send it to you.
Chris -
Is there any way to use a global connection string variable for mysql database.
Currently there are some servlets in my web project.say ,
Servlet_1
Servlet_2
Servlet_3
Now i have to add these lines for each and every servlet to connect with mysql.
String driver = "org.gjt.mm.mysql.Driver";
String url= "jdbc:mysql://localhost/my_db?user=root&password=dba";apart from that if there is a way to create a global connection string servlet or class i can reuse it with my application.
please let me know how to do this.Ok this my Class for connection string.
package org.me.AuthAdmin;
public class ConString
public ConString()
String driver = "org.gjt.mm.mysql.Driver";
String url= "jdbc:mysql://localhost/my_db?user=root&password=dba";
}Please help me on this. i really don't know what to do here after.
package org.me.AuthAdmin;
import java.io.*;
import java.net.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.me.AuthAdmin.ConString;
public class AuthAdmin extends HttpServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
String postUserName = request.getParameter("txt_un").trim();
String postUserPwd = request.getParameter("txt_pwd").trim();
String db_user_name=null;
String db_user_pwd=null;
try
//String driver = "org.gjt.mm.mysql.Driver";
// String url= "jdbc:mysql://localhost/my_db?user=root&password=dba";
Class.forName(driver).newInstance();
Connection con=DriverManager.getConnection(url);
Statement stmt=con.createStatement();
String qStr="SELECT * FROM sysusers WHERE user_name = '"+postUserName+"' AND user_pwd = '"+postUserPwd+"'";
ResultSet rst=stmt.executeQuery(qStr);
while(rst.next())
db_user_name = rst.getString("user_name");
db_user_pwd = rst.getString("user_pwd");
catch(Exception e)
throw new ServletException(e);
if( (postUserName.equals(db_user_name)) && (postUserPwd.equals(db_user_pwd)))
response.sendRedirect("panel.jsp");
}else
response.sendRedirect("error.jsp");
} -
Unable to connect JSP and MySQL
Hi, I am new to this forum
I've started developing web pages using JSP
I've the problem connecting JSP and MySQL database. I've created the page that retrive records from mysql table. But the connection fail to access to database it gives me this error:
org.apache.jasper.JasperException: Exception in JSP: /retreive_book.jsp:15
The code is:
12: <%
13: //Class.forName("com.mysql.jdbc.Driver").newInstance();
14: Class.forName("org.gjt.mm.mysql.Driver");
15: connection = DriverManager.getConnection(connectionURL,"","");
16: statement = connection.createStatement();
17: rs = statement.executeQuery("SELECT * FROM books_detail");
18: %>
And the connectionURL parameter has this value:
String connectionURL = "jdbc:mysql://localhost:3306/books?username=;password=";
root cause msg is:
java.sql.SQLException: Invalid authorization specification: Access denied for user 'nobody'@'localhost' (using password: NO)
Please can anyone help me. It is 3 days now trying to do that but not succeded yetHi
Yes It is true that my MySQl installation its username is root. So how should put that in the url. Cause I did that but it didn.t work
String connectionURL= "jdbc:mysql://localhost:3306/books?username=root;password=";
If I write in that manner is it correct for root username or should I put a single quote
Thanks -
Sql / msql connection string
Hi
How can i do to connect to a sql or mysql database created in azure pack? the "View info" buttom show the connection string but, the server name is the listener name of my tenant cluster. Is there any option to connect like "publish profile?"
or something like that¨?Hi,
We can find the server name, database name and user name from the connection string. We can connect to the database with the information provided by the connection string.
If you want to connect to the database by API, please refer to the link below,
SqlConnection.ConnectionString Property
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
Best Regards.
Steven Lee Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected] -
Hi,
I need help connecting to a MySQL db through oracle reports using a jdbc connection.
I have downloaded the MySQL JDBC driver:mysql-connector-java-3.0.17-ga-bin.jar.
I can succesfully use it to connect if I write a simple java program. So I know the driver works.
I have set it in my classpath & edited the jdbcpds.conf file by adding the following:
<driver name = "mysql-merant"
sourceDatabase = "other"
subProtocol = "mysql"
connectString = "mainProtocol:subProtocol://databaseName"
class = "com.mysql.jdbc.Driver"
connection = "oracle.reports.plugin.datasource.jdbcpds.JDBCConnectionHandling">
</driver>
When I try to connect, I get the following error, ERR 62002 failed to connect to the data source.
What do I have to do to connect? Is there a way to directly give the connect string?
I can connect to an oracle DB using a the Oracle drivers no problem, why does forms not accept the MySQL driver? What can I do to make this work?
Any help would be appreciated.
Michael Baran
[email protected]With Reports 9i the mysql-connector-java doesn´t work for that. You don´t have to edit the jdbcpds.conf. mysql-merant doesn´t exist. Just download MyODBC conector and then stand up your database in your DSN system. Use the wizard to make a report, then use JDBC Query and using jdbc-odbc driver, fill the fields
then you have connected MySQL
very easy.
I hope this help you
Maybe you are looking for
-
I can't get rid of the previous frame I have used, when I create a new frame with added data the previous frame overlaps with the new frame and it all gets a bit messy !
-
HELP - computer doesn't keep icons in list view, etc from one day to next
Every day when I turn on my MAC (at work), the settings from the previous day are gone. I prefer my files/folders to be in "list" view, but they are always in large icon view and scattered all over the window. Each day I have to change every folder I
-
Had to reinstall Firefox on new drive with new install of Windows 7. Missing all of my profile settings.
-
MM02 Sales view - Create new Cross distribution chain material status
Dear Gurus, I need to CREATE new: - Distribution chain specific material status - Cross distribution chain material status Can anyone please help urgently on this? Many thanks for your help Kind regards Chris
-
Dear all, we have requirement to find out OSB Service Processing time. can you please suggest how we can get this information using OSB Console or if ther are any JMX Api available to get this data. requirement is: to know the actual execution time i