Driver not found - java

I am using SQL Server 2018 and JDK 8.0 along with NetBeans. While connecting to the SQL Server, I am getting a SQL Exception as shown in the img
enter image description here
I am using the following code:
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Connection establishment
Connection con=DriverManager.getConnection("jdbc:sqlserver//DESKTOP-CU5U75J\\SQLSERVER1;","","");
//Statement Object
Statement st=con.createStatement();
//For DML use executeUpdate method of Statement Class
st.executeUpdate("insert into Employee (Employee_Id, Employee_Name) values ("+Integer.parseInt(idTF.getText())+","+nameTF.getText()+")");
//Commit Statement
con.commit();
JOptionPane.showMessageDialog(this, "Message", "The Data is Entered", JOptionPane.INFORMATION_MESSAGE);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}

You have missed colon ':' in your jdbc url,
Connection con=DriverManager.getConnection("jdbc:sqlserver://DESKTOP-CU5U75J\\SQLSERVER1;integratedSecurity=true","","");
It was jdbc:sqlserver//DESKTOP-CU5U75J\\SQLSERVER1; which was supposed to be jdbc:sqlserver://DESKTOP-CU5U75J\\SQLSERVER1;
Also, I suggest you to use PreparedStatement to insert your records.
String sql="insert into Employee (Employee_Id, Employee_Name) values (?,?)";
PreparedStatement stmt=con.prepareStatement(sql);
stmt.setInt(1, Integer.parseInt(idTF.getText()));
stmt.setString(2, nameTF.getText());
stmt.executeUpdate();

Related

java.sql.SQLException: Illegal operation on empty result set with no empty row

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Connection connection;
PreparedStatement ps;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "pokemon12");
ps = connection.prepareStatement("SELECT * FROM users WHERE UserName = ? AND Password = ?");
ps.setString(1, jTextField1.getText());
ps.setString(2, String.valueOf(jPasswordField1.getPassword()));
ResultSet rs = ps.executeQuery();
if(rs.next()){
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
setVisible(false);
NewApplication1 mf = new NewApplication1(rs.getString(1),rs.getString(2));
mf.setVisible(true);
}else{
JOptionPane.showMessageDialog(this, "Username Or Password Are Invalid");
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
} catch (SQLException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
i dont know why i keep getting java.sql.SQLException: Illegal operation on empty result set even tho my sql table isnt empty and the row im trying to get also isnt empty, it happens when i try to select the last and second to last row in the table, excuse my lack of knowledge im very new to sql.

How do I correctly shutdown a derby database?

I have a JavaFX application which uses an embedded database to store all data. Establishing a connection and inserting data works just fine besides the column 'id' auto incrementing by 100 instead of 1. I've read(Wrong auto increment in embedded Derby/ Java DB) that I have to shut down the database properly by using following code in my main class:
#Override
public void stop() {
try {
DriverManager.getConnection("jdbc:derby:"+"db"+";shutdown=true");
}
catch (SQLException sqlException){
sqlException.printStackTrace();
System.out.println("Database shutted down...");
}
}
However it's still incrementing by 100 and I'm not sure why.
My code for establishing a connection and doing inserts:
try {
Connection connection = DriverManager.getConnection("jdbc:derby:db");
connection.setAutoCommit(true);
System.out.println("Connection established");
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO orders(order_name, order_date, price) VALUES (?, ?, ?)");
preparedStatement.setString(1, "TestOrder");
preparedStatement.setDate(2, Date.valueOf(LocalDate.now()));
preparedStatement.setDouble(3, 1.1);
preparedStatement.execute();
preparedStatement.close();
connection.close();
} catch (SQLException throwables) {
System.out.println("Unable to establish connection");
throwables.printStackTrace();
}
And my SQL statement to create the table
DROP TABLE orders;
CREATE TABLE orders(
order_number INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY(START WITH 1, INCREMENT BY 1),
order_name VARCHAR(100),
order_date DATE,
price DECIMAL(4, 2));

Java Insert subquery sql statement for mysql

may i know whats wrong with my insert sql statement at java as the sql statement allows me to insert everything into database, leaving my profilepic empty. Currently, what im trying to do is that, i am trying to duplicate the image from userId=143 into the new user. However, the duplication of image doesn't work at java.
On the other hand, at mysql database registration table, there is data for userId=143 and with image. I tried to execute the following sql statement and it works prefectly as what i wanted.
insert into registration
(profilepic, firstName,lastName,phoneNo,dateOfBirth,displayname,password,
emailAddress, address, interest )
select (select profilepic from registration where userId =
143),'ab','cd',94329,'2016-11-11','af','de','gf','ge','ee' ;
However, it doesn't work if i use the exact format for sql statement at java. I'm not able to figure out what's wrong with my sql statement. Your help will be much appreciated. Thanks.
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// connects to the database
conn = getConnection();
// constructs SQL statement
stmt = conn.createStatement();
String sql1 =" insert into registration (profilepic, firstName, lastName,phoneNo,dateOfBirth,displayname,password,emailAddress, address, interest ) select (select profilepic from registration where userId = 143),?,?,?,?,?,?,?,?,? ";
//Using a PreparedStatement to save the file
PreparedStatement statement1 = conn.prepareStatement(sql1);
statement1.setString(1, firstName);
statement1.setString(2, lastName);
statement1.setString(3, phoneNo);
statement1.setString(4, dateOfBirth);
statement1.setString(5, displayName);
statement1.setString(6, password);
statement1.setString(7,emailAddress);
statement1.setString(8, address);
statement1.setString(9, interest);
//sends the statement to the database server
int row = statement1.executeUpdate();
if (row > 0) {
getServletContext().getRequestDispatcher("/Message.jsp").include(request, response);
// message = "You have successfully registered.";
}
} catch (SQLException ex) {
// message = "You have failed to registered. Please try again.";
// ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
// ex.printStackTrace();
//silent
//message="You have failed to log in";
getServletContext().getRequestDispatcher("/FailedMsg.jsp").include(request, response);
}
}
}
Try modifying your query like below having only a single SELECT statement and avoiding the inner sub-select.
insert into registration
(profilepic, firstName,lastName,phoneNo,dateOfBirth,displayname,password,
emailAddress, address, interest )
select profilepic,'ab','cd',94329,
'2016-11-11','af','de','gf','ge','ee'
from registration
where userId = 143;

Error with Oracle 10g auto-incremented sequence

I created a sequence in Oracle 10g because I have to increase case_number field auto_incremently. But I'm getting an error.
private void button_saveandsubmitActionPerformed(java.awt.event.ActionEvent evt) {
con = JavaConnectDB.ConnectDB();
try{
String sql="insert into FIR_form values(case_number_sequence,?,?,?,?,?,?,?,?,?,?,?)";
pst = (OraclePreparedStatement) con.prepareStatement(sql);
pst.setString(1,text_date.getText());
pst.setString(2,text_district.getText());
pst.setString(3,text_subject.getText());
pst.setString(4,text_description.getText());
pst.setString(5,text_cfullname.getText());
pst.setString(6,text_fhname.getText());
pst.setString(7,text_caddress.getText());
pst.setString(8,text_contact.getText());
pst.setString(9,text_suspectfullname.getText());
pst.setString(10,text_suspectaddress.getText());
pst.setString(11,text_suspectdescription.getText());
rs = (OracleResultSet) pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "the FIR has been added successfully!!!");
con.close();
this.dispose();
}
else{
JOptionPane.showMessageDialog(null, "enter all fields appropriately first!!!");
}
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error occured. try again later !!!");
}
}
The field in the table will not auto-populate because you have defined a sequence. You must either reference the sequence.nextval in your insert statement to insert the value, or add a trigger to the table to populate the column from the sequence.
See this post for an example:

Insertion in Excel failed

I tried inserting data into excel sheet using Java and ODBC, my URL is correct, the query to insert the data is executing, but the values are not inserted into excel sheet, i have made connection to commit and close. kindly help!
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:excelDsn;readonly=false;");
ps = con.prepareStatement("insert into [Sheet1$](FirstName, LastName) values (?,?)");
ps.setString(1, "AA");
ps.setString(2, "BB");
ps.execute();
con.commit();
con.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
for DDL statements like insert,delete and update use ps.executeUpdate();
As your case is to insert so replace ps.execute(); with ps.executeUpdate();

Categories

Resources