I am creating a desktop application, in which I have to log in into SQL Server 2005 on the remote machine and have to create a database, User etc. By using jTDS I am able to create a connection to the database as well as able to execute "SELECT" commnads but not able to execute database commands like- create database, create user etc.
Here is my test code:
public class Test {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "net.sourceforge.jtds.jdbc.Driver";
static final String DB_URL = "jdbc:jtds:sqlserver://10.96.11.31:1433;useNTLMv2=true;domain=myDomain";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL);
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
If you need to create a DB via JDBC then the you'll need a user with permissions to connect to the master database on that server. Create a java.sql.Connection object to the master database then simply create the Statement and execute the SQL:
"CREATE DATABASE MyDB"
I'm a little confused by the question, so I apologize if I misinterpreted it.
Related
I'm trying to connect to an Oracle database using JDBC Driver and I'm handle with an error: "java.sql.SQLException: Invalid Oracle URL specified".
My code is the following:
import java.sql.*;
public class L9
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin;#localhost:1521:xe","user","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from table");
while(rs.next())
System.out.println(rs.getInt(1) + " "+rs.getString(2)+ " "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Anyone knows what is the problem?
It should be
jdbc:oracle:thin:#localhost:1521:xe
instead of
jdbc:oracle:thin;#localhost:1521:xe
(note the : after the "thin")
It is better to use a long format connection URL where you have the ability to pass connection descriptors. Easy Connection URL (jdbc:oracle:thin:#//localhost:1521/myorcldbservicename) ) does establish the connection but does not provide any High Availability capabilities.
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=myhost)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=myorcldbservicename)))
So I'm trying to connect my java code to mysql and when I run the code below nothing prints out not even the error. I'm following a YouTube tutorial and understand everything except where he is getting "jdbc:mysql:" from. Any help would be awesome thanks.
package ztestconnection;
import java.sql.*;
public class Test {
static String Username = "Klongrich";
static String Password = "********";
static String Connection = "jdbc:mysql://localhost:8080/hospital";
public static void main(String [] args){
Connection con = null;
try{
con = DriverManager.getConnection(Connection, Username, Password);
System.out.println("Connected");
} catch(Exception e){
System.out.println(e);
}
}
To connect java application with the mysql database mysqlconnector.jar file is required to be loaded.
1:- Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Before you can open a connection, you need to load the specific driver class, like so:
try
{
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception ex)
{
// handle the error
}
This ensures that java.sql.DriverManager can find the driver class definition.
There's some good example code in the MySQL Connector/J documentation.
As for the jdbc:mysql: part of the DSN (Data Source Name), that's a standard syntax that tells the driver manager and the database that they're opening a JDBC connection to a MySQL database. It will be explained in the Oracle Java documentation.
And Tim has a good point about your variable names. Don't give a variable the same name as a class. Even if it doesn't confuse the compiler, it'll confuse the hell out of the maintenance programmer (you) about a week from now.
I want to access to NexusDB V3 with Java.
So I have a Java project with many files that connects to the database. Can anyone tell me if it is possible to use a Java class file for connecting to the database.
I've tried JDBC connector and the ODBC connector but nothing is working.
I have read about a bridge between them but I don't know how to make it so please help.
public class dbConnect {
public static void connect(){
Connection conn;
Statement stmt;
ResultSet rs;
String sql;
conn = null;
String url = "jdbc:mysql://localhost:3306/db_oopproject";
try{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,"user","12345");
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
sql = "Select * from user_account";
rs = stmt.executeQuery(sql);
}
catch (Exception e){
System.out.print(e.getMessage());
}
}
}
first off, your url contains "mysql", are you sure that will work for the jdbc bridge to connect to NexusDB?
I am trying to connect to mysql on my laptop. using the code I have pasted below. I have added the CLASSPATH containing the full path of the file:
mysql-connector-java-5.1.37-bin.jar
and exported it.But I get persistently the mentioned error. Can somebody tell me, please, what I am missing that makes me to get this error message form my machine.
My machine is Fedora core 21, I am trying to execute the code under the user, and not root, and this is the code i am using and of course the static final variables "user" and "password" are not empty strings as they are here:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
// Database credentials
static final String USER = "";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connect ion
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
I have really tried to include any related information that i could guess it is related. If more information is needed to answer the question I am willingly ready to provide.
the DB_URL should set the port and the database name of MySQL.
just like(windows):
jdbc\:mysql\://111.202.27.131\:3306/bridgeResultDatabase?characterEncoding\=utf8
Here bridgeResultDatabaseis the mysql database name, it works for me.
Hope it helps.
There are some mistakes above.
Update(I try in my windows and using root of mysql in Linux):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public static void main(String[] args) throws ClassNotFoundException, SQLException{
String JDBC_DRIVER="com.mysql.jdbc.Driver";
String DB_URL="jdbc:mysql://192.168.11.52/mysql";
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL,"root","111111");
Statement statement = conn.createStatement();
String hrappSQL = "CREATE DATABASE testDatabase";
statement.executeUpdate(hrappSQL);
}
And I create the database "testDatabase" successfully in my linux mysql.
I have the following code to POST data to a database from a web service. I am using the RESTful web service and I am connecting to a Microsoft Azure Database. I get this error message on the server run mode ->'Resource not available". Can someone help me with this issue ?
#Path("/addcar/{CSID}/{PID}/{LicensePlateNumber}/{RegistrationNumber}/{CarModel}/{MakeYear}")
#POST
#Produces(MediaType.TEXT_PLAIN)
#Consumes (MediaType.APPLICATION_FORM_URLENCODED)
public String insertdata(#PathParam("CSID") String csid,
#PathParam("PID") String pid,
#PathParam("LicensePlateNumber") String lpn,
#PathParam("RegistrationNumber") String rn,
#PathParam("CarModel") String carmodel,
#PathParam("MakeYear") String makeyear) throws ServletException,
IOException, SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
PreparedStatement query = null;
String myString = null;
System.out.println(csid+ ","+ pid +","+lpn + ","+rn + ","+carmodel +","+ makeyear);
//Car car = new Car();
//car.newcar(csid, pid, lpn, rn, carmodel,makeyear);
String DB_URL = "jdbc:sqlserver://nysj1rpznm.database.windows.net:1433;database=gparkdb;user=gpark#nysj1rpznm;password=Technology00000;encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
String USER = "gpark";
String PASS = GlobalUtil.PASS;
try{
//STEP 2: Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql = "INSERT into gpark_cars(CSID,PID,LicensePlateNumber,RegistrationNumber,CarModel,MakeYear) VALUES("+csid+""+ pid +""+ lpn+ ""+ rn+ ""+ carmodel+""+ makeyear+")";
ResultSet rs2 = stmt.executeQuery(sql);
System.out.println(sql);
stmt.executeUpdate(sql);
conn.close();
stmt.close();
conn.close();
}
catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return "Vehilce added";
//System.out.println("Goodbye!");
}