Connecting to a MySQL database - java

I have created a MySQL database. I am building a GUI in java. How can I connect this Java software to the database?

First, you need to add the mysql jdbc driver jar to your project, then you would create a connection as follows:
String url = "jdbc:mysql://yourhost:port/dbname";
Class.forName ("com.mysql.jdbc.Driver"); // to load the driver
Connection conn = DriverManager.getConnection (url, userName, password);
Here yourhost is the name or ip address of the server, port is the port number to which the mysql server is bound, dbname is the name of your database.

using any of the miriad of Java/SQL API, so you can perform normal SQL queries. JDBC is a start

Start using JDBC, it's best for start. Take a look on some tutorials
http://www.tutorialspoint.com/jdbc/jdbc-quick-guide.htm
http://www.jdbc-tutorial.com/

this post has helped me quite alot!
I'm quite 'disapointed' and 'suprised' I suppose that Java doesn't have the fuctionatly of connected to online databases built in.
One thing that would make it better, and please tell me the followings true: the fact that users of my software don't have to do anything special like install any drivers?

I've already added one answer - asking a question but the comments/reply's I got seem to be a bit off topic and now I've commented back asking for the answer to my original question no one seems to be answering (Have a look for your self - see what I mean)
So, the orignal question :: The only thing I want to know;
Do the users of my software I made using JDBC have to do anything special regarding JDBC, or is just me who needs to have JDBC while writting the program?
PS Sorry if I'm a bit pushy or doing things that your not supposed to do - I'm new to this community!

Related

How to create a proper mysql connection

I'm still new to programming. I have created a mysql database. And i'm connecting to it in my java app using local host link like this:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DataTest?allowPublicKeyRetrieval=true&useSSL=false", "root","password");
However, I want my java program to be able to connect to my database on any device.
What should I do? how can I make this happen?
You can use the connection string like below
DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","root");
For more details, you can read the oracle docs from the below link
https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html

Error connecting to Oracle database using JDBC [duplicate]

I am new to Oracle, and am trying to run a simple example code with Java, but am getting this error when executing the code.. I am able to start up the listener via CMD and am also able to run SQL Plus. Can anyone give me a hand and tell me what I might be doing wrong?
Update:
I am using JDBC.
Database is local, and I actually had it working but it stopped working just today. I'm not really sure why though. Would you mind giving me some procedures to follow by since I don't know much.
Either:
The database isn't running
You got the URL wrong
There is a firewall in the way.
(This strange error message is produced by Oracle's JDBC driver when it can't connect to the database server. 'Network adapter' appears to refer to some component of their code, which isn't very useful. Real network adapters (NICs) don't establish connections at all: TCP protocol stacks do that. It would have been a lot more useful if they had just let the original ConnectException be thrown, or at least used its error message and let it appear in the stack trace.)
I had the same problem, and this is how I fixed it.
I was using the wrong port for my connection.
private final String DB_URL = "jdbc:oracle:thin:#localhost:1521:orcll"; // 1521 my wrong port
go to your localhost
(my localhost address) : https://localhost:1158/em
login
user name
password
connect as --> normal
Below 'General' click on LISTENER_localhost
look at you port number
Net Address (ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1522))
Connect to port 1522
Edit you connection
change port 1521 to 1522.
done
Another thing you might want to check that the listener.ora file matches the way you are trying to connect to the DB. If you were connecting via a localhost reference and your listener.ora file got changed from:
HOST = localhost
to
HOST = 192.168.XX.XX
then this can cause the error that you had unless you update your hosts file to accommodate for this. Someone might have made this change to allow for remote connections to the DB from other machines.
I figured out that in my case, my database was in different subnet than the subnet from where i was trying to access the db.
I had this error when i renamed the pc in the windows-properties. The pc-name must be updated in the listener.ora-file
Most probably you have listener configured wrongly, the hostname you specify in connection string must be the same as in the listener.
First check the Firewall and network related issues.
Check if Oracle Listener service is available and running. If not you may use Oracle Net Configuration Assistant tool to add and register new listener.
If the above steps are ok then you need to configure Oracle Listener appropriately. You may use Oracle Net Manager tool or edit “%ORACLE_HOME%\network\admin\listener.ora” file manually.
There are 2 options that need to be considered carefully:
Listening Locations associated with the Listener – Hostname(IP) and Port in Listening Location must exactly match the ones used in the connection string.
For example, if you use 192.168.74.139 as target hostname, then there must be Listening Location registered with the same IP address.
Also make sure the you use the same SID as indicated in Database Service associated with the Listener.
https://adhoctuts.com/fix-oracle-io-error-the-network-adapter-could-not-establish-the-connection-error/
IO Error: The Network Adapter could not establish the connection (CONNECTION_ID=iKQM6lBbSLiArrYuDqud8A==)
if you are facing this issue
1- make sure you have downloaded oracle databases like oracle 11g,19c, 21c, or any latest databases.
2- search for services in your computer or type win+r then services.mis then search for oracleservice you will find orcl or xe or any other sid like oracleserviceorcl;
after that you can test your connection using sql developer, sql plus or cmd
To resolve the Network Adapter Error I had to remove the - in the name of the computer name.
In my case, I needed to specify a viahost and viauser. Worth trying if you're in a complex system. :)
For me the basic oracle only was not installed. Please ensure you have oracle installed and then try checking host and port.
I was having issues with this as well. I was using the jdbc connection string to connect to the database. The hostname was incorrectly configured in the string. I am using Mac, and the same string was being used on Windows machines without an issue. On my connection string, I had to make sure that I had the full url with the appending "organizationname.com" to the end of the hostname.
Hope this helps.
Just try to re-create connection. In my situation one of jdbc connection stopped working for no reason. From console sqlplus was working ok.
It took me 2 hours to realize that If i create the same connection - it works.

Java, SQL Database Connection

I am C# developer and I don't know much about Java, normally in C# when I wanna connect to a database I use the following command:
static SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
I read a tutorial about making database connection (Sql Server 2008) in java in MSDN saying that the address must be declared this way:
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=JavaDB;user=UserName;password=*****";
I would like to if there's any way to declare the url the way I do in C#, I mean instead of
"jdbc:sqlserver://localhost:1433;"
I directly point to the database
"AttachDbFilename=|DataDirectory|\Database.mdf;"
thanks
The first part of the URL is prescribed by the JDBC specification, so all drivers will follow the structure jdbc:<vendor-identifier>:<vendor-specific-url>.
In Java creating the connection (at least via java.sql.DriverManager) is independent of the actual Driver implementation that creates the connection (in C# you create a typed vendor-specific connection).
The first part, jdbc:<vendor-identifier> is used as a selection mechanism so a Driver can quickly decide if it will accept an URL or not. Technically multiple driver implementations could accept an URL and create the connection. The <vendor-identifier> is usually the name of the database or company.
The <vendor-specific-url> will usually follow normal URL conventions (MS SQL Server JDBC URLS are an exception to that).
The format of the Microsoft JDBC driver is:
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
See: Building the Connection URL.
Technically, Microsoft could have allowed only the database name in their <vendor-specific-url> and imply that it uses localhost but they decided not to do that.
The official documentation of the SQL JDBC driver does not mention any such thing
http://msdn.microsoft.com/en-us/library/ms378428.aspx
http://msdn.microsoft.com/en-us/library/ms378672(v=sql.110).aspx
so I assume it is not possible

Play! framework - Cannot connect to database

this is the error I get when I'm trying to connect to my local postgresql db:
Cannot connect to database [default]
this is the database configuration. I'm convinced that there is not typo (fat finger error):
db.default.url="postgres://localhost:5432/myproject/"
db.default.user="postgres"
db.default.pass="mypassword"
db.default.driver="org.postgresql.Driver"
db.default.initSQL="SELECT 1"
where is the problem? with pgAdmin I can connect easily
p.s.
I'm using ubuntu. I've noticed that in order to change to postgres user
I must use "su", otherwise it fails changing the current user.
is that has something to do with play! failure to connect my db?
thanks
There might be two things wrong or at least dubious in your setup.
First: The postgres:... URL syntax is not a plain JDBC URL. This format is not understood by the PostgreSQL JDBC driver. See this answer to a similar problem.
Second: You are trying to use the PostgreSQL superuser account for Play. The superuser account should be used only for administrative work, but not "normal" work. Especially not for work which includes public access to the DB via some webfrontend. Any SQL-Injection attack gives the attacker the golden key to your database - including the nuke to wreck your complete DB cluster at once or install any backdoor into you DB server.
So I recommand, that you create a new user which you configure in your Play! settings.
That said: The default password for the postgres user is not set on Ubuntu. This setup allows login to the DB user only from the same OS user. How you can fix this is explained in this answer.
If these two tips don't help: The error you quoted is very vague. There must be more detailed error logs somewhere. Please find them and attach them to your question with the "edit" button.
This is not an answer directly to your question, but I had the same error message and came here via Google. Using Scala Play 2.3, I had
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://127.0.0.1:5432/noob_development"
db.default.logStatements=true
which needed to be
db.default.driver="org.postgresql.Driver"
db.default.url="jdbc:postgresql://127.0.0.1:5432/noob_development"
db.default.logStatements=true
I accidentally left the quotes around the driver name out. Now it works perfectly.
here is my conf, it works:
db.default.url="jdbc:postgresql://127.0.0.1:5432/dbname"
db.default.driver="org.postgresql.Driver"
just add the jdbc: before postgresql in db.default.url.

ODBC Connection Setup in Java

I want to write a Java program that automates the work that the ODBC Data Source Administrator does in Windows.
That is, given an ODBC connection name and a path to the database on the hard drive, I want it to create the connection.
I really have no idea where to even begin with this. I looked at this but it said it was for C and I don't think that's very helpful. If anyone could point me in the right direction for this at all, I would appreciate it.
(I realize this question is REALLY vague, but that's all the information I was given.)
The answer to the question is that you don't need a registered DSN.
Here is an example of using a ODBC connection (not JDBC) from Java, using the system ODBC driver. Instead of editing the registry to create a registered DSN, your alternative is to use a un-registered DSN, like so:
Driver=sun.jdbc.odbc.JdbcOdbcDriver
Source=jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Dir/DB/MyDB.mdb;
Or, using SQL Server:
Driver=sun.jdbc.odbc.JdbcOdbcDriver
Source=jdbc:odbc:Driver={SQL Server};SERVER=127.1;DATABASE=MyDB;UID=sa;PWD=mypass
All ODBC configuration is in Windows registry or odbc.ini in Linux (I haven't used ODBC on other platforms). At first you must create such configuration using ODBC manager, then check what was saved in configuration and write program that do the same. If you work with Windows 32 bit, then check registry at HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
Windows 64 bit have different configurations for 32 bit apps and 64 bit apps (just look for odbc.ini string in registry).
I think Java is not the best language to change something in Windows registry, but with Java you can create .reg text file that can be imported by regedit.exe, or you can use other language like Python with win32 extensions (Active Python has it by default).
You will want to look into using JDBC.
String driver ="sun.jdbc.odbc.JdbcOdbcDriver"
String url = "jdbc:odbc:Driver={Microsoft Access Text Driver (*.txt, *.csv)};DBQ=C:/CSVFolder
query = select * from myfile.csv
Check this one out..
Java Database Connectivity (JDBC) supports ODBC-based databases and provides a independent database.
Connection connection = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection("connection string", "userName", "password" );
} catch (SQLException e) {
}
return connection;
I've never had to connect to MS SQL Server before. I've always used DB2 or Derby, MYSQL and everything was always the same for creating a connection. This is what I had to do for SQL Server.
private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
url="jdbc:odbc:;DRIVER={SQL Server};SERVER="+server+","+port+";DATABASE="+dbName;
connection = DriverManager.getConnection(url,user,password);

Categories

Resources