In JDBC, I want to insert data using input from the keyboard.
As a result of finding the method, I came to know the scanner and wrote the code as follows.
package DB;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
class insert{
Connection con;
Statement stmt;
Scanner scan = new Scanner(Syetem.in);
public insert() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#localhost:1521:orcl";
con = DriverManager.getConnection(url,"scott","1234");
stmt = con.createStatement();
} catch(ClassNotFoundException ce) {
System.out.println(ce.getMessage());
} catch(SQLException se){
System.out.println(se.getMessage());
}
}
public void disconnect() throws SQLException{
if (stmt!=null) stmt.close();
if (con!=null) con.close();
}
public void insert() throws SQLException{
System.out.println("name:")
String employee_name=scan.next();
System.out.println("domain:")
String street=scan.next();
System.out.println("country:")
String city=scan.next();
String sql="insert into information values('"+name+"', '"+domain+"', '"+country+"')";
int n=stmt.executeUpdate(sql);
}
}
But it didn't run and got an error ...
The default method cannot be found in the class. Define a default method in the following format. public static void main (String [] args)
Where should I put the main function to fix the error?
What is the problem? The name of the table to be inserted is 'information'.
Any help would be greatly appreciated
Because JDBC is not yet familiar, if possible, if you write a full query including a connection as in the above query, I would be very grateful.
*my oracle version is 11g
For your code to run you need to provide a method that works as an entry point for your program, that method has the signature public static void main(String[] args) besides that, your class should be named Insert with capital I first because thats de standard y second because you have a method called insert, you will need to have something like this:
public class Insert {
public Insert() {
...
}
public void disconnect() throws SQLException {
...
}
public void insert() throws SQLException {
...
}
public static void main(String[] args) {
new Insert().insert();
}
}
Related
i guess this is a newbie question...Don't seem to find it anywhere, so i thought i asked, hope you don't get mad :) I am really new to all this jsp and java thing and try to figure out what's going on.
So, I have created 2 classes that create the connection to my postgres database. The thought was to have a class that creates the connection and use it anytime i need it, cause i will need to retrieve data many times in the future.
The first one: DbContract.java
package Database;
public class DbContract
{
public static final String HOST = "jdbc:postgresql://localhost:5432/";
public static final String DB_NAME = "DB_1";
public static final String USERNAME = "postgres";
public static final String PASSWORD = "12345";
}
and the second one: TestConnection.java
package Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestConnection
{
public static void main(String[] args)
{
try
{
Class.forName("org.postgresql.Driver");
Connection c;
c = DriverManager.getConnection(
DbContract.HOST+DbContract.DB_NAME,
DbContract.USERNAME,
DbContract.PASSWORD);
System.out.println("DB connected");
}
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
}
}
Now, i want to use these, in order to retrieve data from a existing database i have (postgres and it is filled with records.), BUT from a jsp page. Is it possible?
Can anyone, help me step by step to do it, or is it too easy?
thanks in advance
it seems my code is not working. I am trying to extract data from microsoft NAV Cronus DB, but it appears JAVA can't find the table to print.
So I have 2 classes - DAL & Controller
DAL:
import java.sql.*;
public class DAL {
private static String connStr = "jdbc:sqlserver://Localhost;Databases=CronusDB;user=root;password=root;";
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(connStr);
}
public static ResultSet findEmployeeData() throws SQLException {
Statement stmt;
stmt = getConn().createStatement();
String sqlStr = "select [No_], [First Name], [Last Name], [Initials], [Job Title] from [CRONUS Sverige AB$Employee];";
ResultSet rset = stmt.executeQuery(sqlStr);
return rset;
}
}
Connector:
import java.sql.*;
import t3.isprojekt.uppg2.dal.DAL;
public class Controller {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
DAL.getConn();
System.out.println("Connection Success!");
System.out.println(DAL.findEmployeeData());
}
}
When trying to execute the code I recieve the following error:
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'CRONUS Sverige AB$Employee'.
The problem is that the table does exist, and I have tried putting .dbo in front without success. Any ideas?
It seems like the database is very sensitive to upper- & lowercase letters. The tables are listed as "CRONUS Sverige..." in MSSQLServer, but when copying the name directly into JAVA it is pasted as "CRONUS SVERIGE" (uppercase). So finally got this working!
I am having really strange problem. I have just written a code that should create procedure and then execute it. But it is giving me this error:
Exception in thread "main" java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access] Syntax error in statement CREATE TABLE
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at mDat.procedures.createProcedure(procedures.java:25)
at mDat.procedures.main(procedures.java:14)
Here is my code:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class procedures {
static Connection con;
static String procedure;
public static void main(String[]args) throws ClassNotFoundException, SQLException{
getConnection("jdbc:odbc:TestDatabaze");
createProcedure();
executeProcedure();
con.close();
}
static void getConnection(String connection) throws ClassNotFoundException, SQLException{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(connection);
}
public static void createProcedure() throws SQLException{
procedure="CREATE PROCEDURE newest_user AS SELECT Firstname, Lastname FROM members WHERE ID= max(ID)";
Statement s = con.createStatement();
s.execute(procedure);
s.close();
}
public static void executeProcedure() throws SQLException{
CallableStatement cs=con.prepareCall("{CALL newest_user}");
String fn=cs.getString(1);
String ln=cs.getString(2);
System.out.println("Name of the newest user in database is "+fn+" "+ln);
}
}
I really have no idea why it is giving me that error, becouse there is no code for creating table. Thank you for your help.
I want to insert some informations in my dataBase "sqlserver" via NetBeans!!!the connection is good but don't know what's the pb,realy this pb make me crazy!!!!!!!
Please help me!!!!
CODE:
package Conn;
import java.sql.Connection;
import java.sql.*;
import javax.swing.JOptionPane;
/**
*
1. #author Nadia
*/
public class Connexion {
java.sql.Connection C;
private Connection C1;
String Nom;
String Adresse;
String MDP;
String VMDP;
/**
* Constructeur`enter code here`
*/
public Connexion() {
//this.connection=ConnexionBDD.getInstance();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
C1=DriverManager.getConnection("jdbc:sqlserver://localhost\\A:1433databaseName=Authentif","sa","sqlserver");
Statement stmt = C1.createStatement();
}
catch(Exception e){}
}
//*************Insertion Utilisateur
// public int insertUtilisateur(UserIdentit utilisateur) {
public void insertUtilisateur(String Nom,String Adresse,String MDP,String VMDP) {
PreparedStatement pst;
try {
**pst = C1.prepareStatement("INSERT INTO Authentif.dbo.tab_authentif (Nomc,Adressec,MDP,VMDP)"+"VALUES(?,?,?,?)");** *(ligne 50)*
pst.setString(1,Nom);
pst.setString(2,Adresse);
pst.setString(3,MDP);
pst.setString(4,VMDP);
int res=pst.executeUpdate();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
Follow the SQL Server documentation
You need to add a semi-colon before the database key-value pair:
jdbc:sqlserver://localhost\\A:1433;databaseName=Authentif
^
This is causing the Connection to be null here. No exceptions message appears as the exception is being silently caught. Add some form of notification such as a printStackTrace call. Finally, catch the most specific exception, in this case, an SQLException. This allows the application to handle database specific exceptions.
I have written a connection code with oracle. But still I am getting errors. I'll type the code of mine here.
import java.sql.*;
public class SimpleOraJava {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
String serverName="10.20.228.67";
String user="root";
String password="root";
String SID="abc";
String URL="jdbc:oracle:thin:#"+serverName+":"+1520+":"+SID;
Connection conn=DriverManager.getConnection(URL, user, password);
String SQL="Select employeename from employee";
Statement stat=conn.createStatement();
ResultSet rs=stat.executeQuery(SQL);
while (rs.next()){
System.out.println(rs.getInt(1));
}
stat.close();
conn.close();
}
}
It shows error in this line:
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
The error is on the word Oracle. It is asking me to create class in package oracle.jdbc.driver
Please somebody help!
Okay, assuming that class-paths are set up, and the appropriate .jar files are in the correct directories, the first thing that jumps out is I believe you need to import the package into your class. There should be a import oracle.jdbc.driver.*; line under the import java.sql.*; line also the DriverManager call should be
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
with the lowercase o, it's capitalized in your code.
Another thing might be, the version of the Oracle JDBC, and Oracle client you're using. According to this OTN Discussion post Oracle JDBC 10.2 is the last release to support the package oracle.jdbc.driver.
So basically according to the metalink page if you're using a JDBC 10.2 or older client, something like this will work:
import java.sql.*;
import oracle.jdbc.driver.*;
public class myjdbcapp
{
public static void main(String[] args) throws SQLException
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
String url = "jdbc:oracle:thin:#server:port:orcl";
String userName = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection (url, userName, password);
OracleCallableStatement myprocst = (OracleCallableStatement)
conn.prepareCall ("begin myproc(?); end;");
// ...
}
}
Clients newer than JDBC 10.2 will need to change import oracle.jdbc.driver.; to import oracle.jdbc.;
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
The package is oracle.jdbc.driver with a lowercase o.