I'm new to java and sql, I'm trying to connect to the postgresql program but I get an error and nothing happens. I can't figure out what's wrong
Unused import statement
Class 'ConnectPG' is never used
Method 'connectBD()' is never used
Method 'disconnection(java.sql.Connection)' is never used
I have two java class files, one "ConnectPG" I want to connect to postgresql through it, and the file "insertRecordExample" through it I try to enter values into the table. But nothing works. When I start debugging SEPARATELY on the "insertRecordExample" file, the program gives an error:
"
16:53:59: Executing ':app:InsertRecordExample.main()'...
enter code here`FAILURE: Build failed with an exception.
Blockquote
Where:
Initialization script 'C:\Users\fff\AppData\Local\Temp\InsertRecordExample_main__.gradle' line: 41
What went wrong:
A problem occurred configuring project ':app'.
Could not create task ':app:InsertRecordExample.main()'.
SourceSet with name 'main' not found.
Try:
Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.
Get more help at https://help.gradle.org
BUILD FAILED in 110ms
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
See https://docs.gradle.org/7.4/userguide/command_line_interface.html#sec:command_line_warnings
16:54:00: Execution finished ':app:InsertRecordExample.main()'.
"
Java File ConnectPG:
package com.example.a112new;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
public class ConnectPG {
Connection connect=null;
public Connection connectBD(){
try{
Class.forName("org.postgresql.Driver");
// localhost
connect=DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/112", "postgresql", "430890");
}catch (Exception er) {
System.err.println(er.getMessage());
}
return connect;
}
//
protected void disconnection(Connection con)throws Exception {
con.close();
}
}
Java File InsertRecordExample:
package com.example.a112new;
//package net.javaguides.postgresql.tutorial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Insert PrepareStatement JDBC Example
*
* #author Ramesh Fadatare
*
*/
public class InsertRecordExample {
//localhost
private final String url = "jdbc:postgresql://127.0.0.1:5432/112";
private final String user = "postgres";
// root
private final String password = "111111";
private static final String INSERT_USERS_SQL = "INSERT INTO users" +
" (user_id, lastname, firstname, patronymic, birth,phone,email,password) VALUES
" +
" (?, ?, ?, ?, ?, ?, ?, ?);";
public static void main(String[] argv) throws SQLException {
InsertRecordExample createTableExample = new InsertRecordExample();
createTableExample.insertRecord();
}
public void insertRecord() throws SQLException {
System.out.println(INSERT_USERS_SQL);
// Step 1: Establishing a Connection
try (Connection connection = DriverManager.getConnection(url, user, password);
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "FFFF");
preparedStatement.setString(3, "FFFF");
preparedStatement.setString(4, "FFFFF");
preparedStatement.setString(5, "2005-01-12");
preparedStatement.setString(6, "+79888888888");
preparedStatement.setString(7, "11111#gmail.com");
preparedStatement.setString(8, "1234567");
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
preparedStatement.executeUpdate();
} catch (SQLException e) {
// print SQL exception information
printSQLException(e);
}
// Step 4: try-with-resource statement will auto close the connection.
}
public static void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}}
Please help me understand what I am doing wrong.
I tried to identify the problem through logcat "--warning-mode=all" But it's no use, it doesn't give any errors at all. Gives errors only InsertRecordExample when I run it ONE! If I run the entire program, there are no errors as such, only those that I described above. I apologize in advance for my English.
If you are using android emulator to test your app then you shouldn't use 127.0.0.1 in your connection string, but 10.0.2.2, because if you are running both your server and your emulator on the same machine the 127.0.0.1 will refer to the emulator itself.
But generally JDBC doesn't work well at all when it comes to Android, so it may not be your mistake, but simply that JDBC doesn't work correctly. The best way of connecting to your database is using web services.
Related
im trying to connect to mysql database and manipulate the data in it but when i try to run my code it get the error, driver [java application] C:\program files\java\jre 1.8.0_111\bin\javaw.exe from what ive been reading its because its launching javaw and not java.exe but i cant seem to figure out how to switch to that can anyone help me?
package jdbc;
import java.sql.*;
public class Driver {
public static void main(String[] args) {
try
{
//get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cs160test");
//create a statement
Statement myStmt = myConn.createStatement();
//execute the sql query
ResultSet myRs = myStmt.executeQuery("select * from genre");
//process the result set
while(myRs.next())
{
System.out.println(myRs.getString("name"));
}
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
}
That is no error. It is telling you that your program exited because there wasn't further instructions to follow.
<terminated> main [java application] path\bin\javaw.exe
I reproduced this behavior and the only way this is happening is if your genre table has no records.
Ensure that all your classes are saved, including the one with the main method. If that does not work, close Eclipse and reopen it.
Question has been updated (The DriverManager is no longer loaded manually and instead the getConnection() method is used):
package guii;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* This program demonstrates how to establish database connection to Microsoft
* SQL Server.
* #author www.codejava.net
*
*/
public class JdbcSQLServerConnection {
public static void main(String[] args) {
Connection conn = null;
try {
String dbURL = "jdbc:sqlserver://ASUS\\YES:1433";
String user = "TestingUser";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
if (conn != null) {
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " + dm.getDatabaseProductName());
System.out.println("Product version: " + dm.getDatabaseProductVersion());
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
The problem is the resulting Exception of this code. I can't find out know the reason why that particular exception is thrown.
The username, password and servername were double checked and they are definitively correct.
Currently this exception is thrown:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'TestingUser'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2532)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1929)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1917)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1061)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at guii.JdbcSQLServerConnection.main(JdbcSQLServerConnection.java:25)
Trouble Shooting Notes
Use integratedSecurity=true again
Check if you have the sqljdbc_auch.dll in your system32 folder
Check out this link
Make sure you use the correct one (32 vs 64 bit)
Make sure the sqljdbc_auch.dll is in the Windows system path
Check if the properties of your Server instance are set correctly: access rights, make sure it actually listens in the port 1433, ...
check out this link and don't just look at the accepted answer but the other two as well.
make sure your firewall does not prevent any connections
check out if your Java Version matches the jdbc Version you use sqljdbc4.2 needs Java 1.8, jdbc4.1 needs java 1.7. look here
I am trying to manipulate a MS Access database with java without ODBC and I've tried following the instructions over at Manipulating an Access database from Java without ODBC but I keep on getting the error:
Error connecting net.ucanaccess.jdbc.UcanaccessSQLException: user lacks privilege or object not found: EMPLOYEE
I have already added the necessary JAR files to the library so I believe that something is wrong with my code or database. I am fairly new to databases and running Java SE 8 and using the NetBeans IDE 8.0.
The code is below
package javaapplication1;
import java.sql.*;
public class Dbase {
public static void main(String[] args) {
try {
Connection c = DriverManager.getConnection(
"jdbc:ucanaccess://C:/Users/nevik/Desktop/databaseJava/Employee.accdb");
Statement s = c.createStatement();
ResultSet resSet = s.executeQuery("SELECT [FNAME] FROM [Employee]");
while (resSet.next()) {
System.out.println(resSet.getString(1));
}
}
catch (SQLException sqle) {
System.err.println("Error connecting " + sqle);
}
}
}
previously i using this code to connect my database there is non error occur.
but comes to this DA files, its unable to connect to database.
i had go through most of the post but some of it i don't understand.[i'm just new to java]
i had try to use jdbc:derby://localhost:1527/societydb;create=true
but the same error occur again.
here's the code and <<< is the line the error point to.
private String host = "jdbc:derby://localhost:1527/societydb";
private String user = "nbuser";
private String password = "nbuser";
private String tableName = "MEMBER";
private void createConnection() {
try {
conn = DriverManager.getConnection(host, user, password);
System.out.println("*** Successfully established the connection to database. ***");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
public ArrayList<Member> getMember() {
ArrayList<Member> memArray = new ArrayList<>();
try {
stmt = conn.prepareStatement("SELECT * FROM " + tableName);//<<< error pointing to here
ResultSet rs = stmt.executeQuery();
while (rs.next()){
Member m = new Member(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getInt(9), rs.getString(10), rs.getString(11));
memArray.add(m);}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error Message", JOptionPane.ERROR_MESSAGE);
}
return memArray;
}
From Java documentation the drivers you need are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver.
Also it clearly states
Any JDBC 4.0 drivers that are found in your class path are automatically loaded.(However,
you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)
Note : JDBC 4.0 comes as a default package from Java 7 onwards.
As for your problem search for the classes mentioned above in your class path(Ctrl + N in Intellij Idea or Ctrl + R in Eclipse). If these classes are not present google them, download and add the jar files to your class path.
Just add these external jars:
derby.jar
derbyclient.jar
How to do it:
right click your project > Properties > Java Build Path > Libraries
click 'Add external jar'
go to C:\Program Files\Java\jdk1.8.0_65\db\lib
add the derby.jar and derbyclient.jar
I'm using MySQL 5.5 with its defaults. I created a user/password and ran a script creating a database called employees. Through the command prompt I can access the database:
mysql -u user -p
SELECT * FROM employees
In my Java application, I am unable to connect. I have tried these URLs, as well as others, but nothing works:
"jdbc:mysql://localhost/employees" "user" "password"
"jdbc:mysql://localhost:3306/employees" "user" "password"
"jdbc:mysql:///employees?user=user&password=password"
Here's the relevant code:
public Main()
{
try {
connection = DriverManager.getConnection(url);
//connection = DriverManager.getConnection(url, user, password);
// I don't know what else to try
} catch (SQLException ex) {
System.out.print(ex + "\n\n");
}
}
Make sure you have Mysql driver jar in the class path and check MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html
The error tells me that either
ConnectorJ driver is not in your classpath.
OR
When using DriverManager, the jdbc.drivers system property has not been populated with the location of the Connector/J driver.
OR
The format of your connection URL is incorrect, or you are referencing the wrong JDBC driver.
In your scenario, it is the list item #1 which is the cause of the issue you are facing.
I would use something like below code snippet to get the connection object.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Connection conn = null;
...
try {
conn =
DriverManager.getConnection("jdbc:mysql://localhost/employees?" +
"user=user&password=password");
// 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());
}