I have written a simple Java file to handle some SQL that is integrated with SQL server.
I downloaded the appropriate driver and stored the JAR in the correct class path however it only works if I run the file directly.
I have tried calling methods within the sql class from another class and i get the following error:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
I understand that this issue is well documented but it doesn't address my unique problem which is that it works within the file but not externally.
Another issue is that after the program is closed and rebuild my program forgets that the JAR was added as a library and requires me to add it again which is not good.
I have tried adding the class path by manually copying and pasting it into an XML config file but this is a hacky solution and I would rather do it properly. Please let me know where I am going wrong.
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.ow2.asm/asm/5.0.4/da08b8cce7bbf903602a25a3a163ae252435795/asm-5.0.4.jar!/" />
<root url="jar://$USER_HOME$/IdeaProjects/r3prototypingCFS/contracts/src/main/kotlin/com/r3corda/protocols/sqljdbc42.jar!/" />
</CLASSES>
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Use jdts driver ..it work with Sql Server 2014.
pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
and src
import java.sql.*;
public class Main {
public static void main(String[] args) throws SQLException {
// write your code here
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/DATABASENAME";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "username";
String password = "yourpassword";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
Statement stmt = conn.createStatement();
String sql = "SELECT top 10 PhoneNumber,RegistrationDate\n" +
" \n" +
" FROM tblProductRegistration";
// ResultSet resultSet = stmt.executeQuery(sql);
// String selectSQL = "SELECT USER_ID, USERNAME FROM DBUSER WHERE USER_ID = ?";
//Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
// preparedStatement.setInt(1, 1001);
// ResultSet resultSet = preparedStatement.executeQuery( );
//STEP 5: Extract data from result set
while(resultSet.next()){
//Retrieve by column name
String PhoneNumber = resultSet.getString("PhoneNumber");
String RegistrationDate = resultSet.getString("RegistrationDate");
//Display values
System.out.print("PhoneNumber: " + PhoneNumber);
System.out.print("RegistrationDate: " + RegistrationDate);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}
Related
New to JDBC and trying to connect to data base in MySql workbench. Following is the Java code
import java.sql.*;
public class Demo {
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306//students?useSSL=false";
String user = "root";
String password = "root";
String query = "Select * from students";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rt = st.executeQuery(query);
rt.next();
String name = rt.getString("stu_name");
System.out.println(name);
st.close();
con.close();
}
}
Following is the error being thrown:
Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the main URL sections.
My MySQL workbench version is 8.0.21 with same version for mysql-connector/J
I assume the problem is the double slash (//) in your URL. Try
String url = "jdbc:mysql://localhost:3306/students?useSSL=false";
instead.
I am trying to write code for bringing a text file's data into a database using Eclipse, MySQL Workbench, and JDBC 8.0.11. It is giving me a ClassNotFoundException. I have looked at multiple other questions, and they have all been fixed by putting the java\com\mysql\jdbc\Driver.java inside the DriverManager.getConnection parameter. I have already done that, and it is still giving me an error. Anyone have any ideas as to why I'm still getting this error?
public static void main(String[] args) throws Exception{
Class.forName //Register JDBC Driver
("*mysql-connector-java-8.0.11.\\src\\legacy\\java\\com\\mysql\\jdbc\\Driver.java*")
.newInstance();
conn = DriverManager.getConnection (url, user, pass);
Statement stmt = conn.createStatement();
String mysql1 = "UPDATE Policy SET " + readAndArray //Changeable file path
("filepath");
}
NEW EDIT
Following #zlakad 's advice, it turns out that you don't need to use Class.forName() if you have Java 6 or higher. Although, now I have a new error: SQLNonTransientConnectionException because of the underlying WrongArgumentException. I'm puzzled as to why it does this because I'm not using the incorrect parameters for DriverManager.getConnection. Any suggestions?
String url = "file path"; //Changeable for MySQL DB
String user = "root";
String pass = "password";
public static void getConnection() throws Exception {
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
Try this:
// None of this belongs in a main method.
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
// where are url, user, pass set? I don't see them.
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
// this is simply wrong.
String mysql1 = "UPDATE Policy SET " + readAndArray("filepath");
}
You're new to Java and JDBC. This is not a good way to do it. I'd recommend that you search the web and SO for some examples of how to do it better.
You have to load driver class for connection not jar file of that class
you shoud try this:
Class.forName("com.mysql.jdbc.Driver");
I was using the wrong format for a database url in the DriverManager.getConnection();
I changed my url to a jdbc:mysql://host:3306/ and it worked.
String url = "jdbc:mysql://*host*:3306/";
Connection conn = DriverManager.getConnection(url, user, pass);
I'm having problems trying to connect to a PostgreSQL database via JDBC in a Java EE web application. The same code that I'll show works on Netbeans and Eclipse, but not on IntelliJ.
My Java EE application have the following servlet:
PrintWriter writer = response.getWriter();
writer.println("<!DOCTYPE HTML>");
writer.println("<html>");
writer.println("<body>");
writer.println("<h1>TEST H1</h1>");
writer.println("<ul>");
writer.println("<li>TESTE LI</li>");
writer.println("<p>" + ConexaoBD.getName() + "</p>");
writer.println("</ul>");
writer.println("</body>");
writer.println("</html>");
where I am making a link to a class named 'ConexaoBD', with a method getName() that returns a string from a database table (just to test).
Here's my method getName(). It works on a console app, but not on Java EE.
Connection con = null;
Class.forName("org.postgresql.Driver");
Properties props = new Properties();
String url = "jdbc:postgresql://localhost/customers";
props.setProperty("user","postgres");
props.setProperty("password","pass");
props.setProperty("ssl","true");
con = DriverManager.getConnection(url, props);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from table limit 1");
return rs.getString(2);
This is not how you connect to a database in a Java EE application.
Typically, you would have code that looks something like:
public class SomeService {
#Resource(name="java:global/jdbc/myDataSource")
private DataSource ds;
public String performSomeQuery(...) {
try (Connection con = ds.getConnection();
Statement st = con.createStatement()) {
ResultSet rs = st.executeQuery("select * from table limit 1");
return rs.getString(2);
}
}
}
The DataSource with name="java:global/jdbc/myDataSource"is configured in your application server according to its documentation. This configuration will include the such things as the JDBC URL and authentication information.
Can you post the error stack trace. Meanwhile check if the driver jar is added in the classpath(Lib folder) appropriately .
I am trying to insert data into Derby embedded database for my Desktop Application. But Derby is giving me error of Schema Not found error.
I have tried to solve error by creating schema as per username, but does not solve my problem. I searched internet, but none of given solution solved my problem.
package derbyd.ui;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class AddStudent extends javax.swing.JFrame {
private void bt_saveActionPerformed(java.awt.event.ActionEvent evt) {
String conURL = "jdbc:derby:myDB;create=true";
String user = "SOURABH";
String passwd = "pass";
Connection con = null;
Statement st = null;
String query;
ResultSet rs = null;
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection(conURL, user, passwd);
st = con.createStatement();
System.out.println("Connection established");
query = "INSERT INTO SOURABH.MyTable VALUES('"+txt_name.getText()+"','"+txt_surname.getText()+"')";
st.executeUpdate(query);
System.out.println("Added Successfully");
}
catch(Exception e)
{
System.out.println("Error ->"+e);
}
}
}
According to the Frequently Asked Questions of Apache Derby, you will see that:
A schema is only created by CREATE SCHEMA or creating an object (table etc.) in that schema (this is implicit schema creation).
In your code, you need create the table first and then work like a charm.
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection(conURL, user, passwd);
st = con.createStatement();
System.out.println("Connection established");
st.executeUpdate("CREATE TABLE MyTable" +
"(name VARCHAR(255), surname varchar(255))");
System.out.println("Table created");
query = "INSERT INTO SOURABH.MyTable VALUES(" +
"'" + txt_name.getText() + "','" + txt_surname.getText() + "')";
st.executeUpdate(query);
System.out.println("Added Successfully");
The output is:
Connection established
Table created
Added Successfully
If you run this statement more than once, you'll get an error because the table already exists. To deal with that, here.
the easiest solution is to configure your database properties and make schema the same as user name but in capital litters
ex:
schema APP
user app
hope my answer can help.
I'm trying to connect Java and MySQL with JDBC connector. So, I've downloaded connector from official cite, added it to classpath and added to the libraries of eclipse.
Now i'm using the code below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class LocalhostDBConnection
{
LocalhostDBConnection()
{
Connection connection;
try {
// Название драйвера
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
// Create a connection to the database
String serverName = "localhost";
String mydatabase = "AvtoKovriki";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "root";
String password = "";
connection = DriverManager.getConnection(url, username, password);
System.out.println("is connect to DB" + connection);
String query = "Select * FROM users";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.execute(query);
String dbtime;
while (rs.next())
{
dbtime = rs.getString(1);
System.out.println(dbtime);
} // end while
connection.close();
} // end try
catch (ClassNotFoundException e)
{
e.printStackTrace();
// Could not find the database driver
} catch (SQLException e)
{
e.printStackTrace();
// Could not connect to the database
}
}
}
But in string: ResultSet rs = stmt.execute(query); there is a mistake "Type mismatch: cannot convert from boolean to ResultSet".
I can't understand what the problem is. Need some help.
The Statement#execute method returns a boolean. You are looking for the Statement#executeQuery method, which returns a ResultSet.
Your code should be like this:
ResultSet rs = stmt.executeQuery(query);
Firstly, this has nothing to do with MySQL - you're not getting as far as running the code, and none of your code deals with MySQL-specific types. (My point is that you may or may not have the MySQL jar file in the right place; this error isn't due to that.)
If you look at the documentation for Statement.execute(String) you'll see that that returns boolean, not ResultSet. That's why you're getting the compile-time error.
You want executeQuery(String) instead - or you could call execute(String), and if it returns true, call getResultSet.
You need to use executeQuery(String sql) method
see javadocs for more details about the provided methods
http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html
stmt.execute(query);
returns boolean not ResultSet. You can get
ResultSet by using stmt.executeQuery() method for queries that won't
modify data in the database.
If you want to modify data in your Database use the executeUpdate() method, which will return an integer to indicate whether data has been modified or not.