java.io.NotSerializableException: net.sourceforge.jtds.util.BlobBuffer$BlobInputStream - java

I have a database on a server, and to connect with him use RMI. I created the following method in the RMI server:
public InputStream getImageById(int id) {
try {
String sql = "SELECT photo FROM Product WHERE id = ?";
PreparedStatement ps = SQLConnection.getConnection().prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
return rs.getBinaryStream("photo");
}
Log.message("Retonada imagem (ID: " + id + ")");
} catch (SQLException e) {
Log.message("Ocorreu um erro. (getImageById) " + e.getMessage());
}
return null;
}
But when calling the error is occurring below, someone can tell me what it is?
SEVERE: null
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: net.sourceforge.jtds.util.BlobBuffer$BlobInputStream
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:191)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at com.sun.proxy.$Proxy0.getImageById(Unknown Source)
at model.teste.main(teste.java:22)
Caused by: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: net.sourceforge.jtds.util.BlobBuffer$BlobInputStream
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1352)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:324)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:173)
... 4 more
Caused by: java.io.NotSerializableException: net.sourceforge.jtds.util.BlobBuffer$BlobInputStream
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1181)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at sun.rmi.server.UnicastRef.marshalValue(UnicastRef.java:292)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:332)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724

It appears that you may be attempting to pass a BlobBuffer.BlobInputStream as an argument or result of an RMI call.
And I suspect that it is actually the object returned by rs.getBinaryStream("photo") which is unlikely to be Serializable.
Passing a Stream object of any kind via RMI is unlikely to work without a LOT of work. A better idea (in this case) would be to fetch the blob into memory as a byte[] and return that via RMI.

Related

DriverManager.getConnection error java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long [duplicate]

This question already has answers here:
ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long on connect to MySQL
(6 answers)
Closed 2 years ago.
I was tryng to learn how to connect to mysql from an desktop java application, but there is something wrong with the connection method Class.forName("com.mysql.jdbc.Driver");
When I call it returns this expection :
java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
I reinstalled the J/connection (I couldn't download it alone, it comes with the other drivers in the installer, I added the driver as a library and i Tried using the com.mysql.jdbc.Connection, and the java.sql.Connection class. The two of them throw the same error. I looked for other similar questions and none of those solved the problem, what else can I do? where can I download an old J/Connection driver ? should I reinstall the whole netbeans?
I wonder...
these are my methods with the unnecessary code commented:
public static final String URL = "jdbc:mysql://localhost:3306/escuela";
public static final String USERNAME = "root";
public static final String PASSWORD = "123";
public static Connection getConnection(){
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(URL, USERNAME, PASSWORD); //here
fails.
JOptionPane.showMessageDialog(null, "Conexion exitosa.");
}
catch(Exception e){
e.printStackTrace();
}
return con;
}
private void btnConectarActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = getConnection(); //I call the connection here
// Statement st;
// ResultSet rs;
//
// try{
// st = con.createStatement();
// rs = st.executeQuery("SELECT * FROM personas");
//
// while(rs.next()){
// JOptionPane.showMessageDialog(null, rs.getString("nombre")
// + " " + rs.getString("telefono"));
// }
// con.close();
// }
// catch(Exception e){
// System.out.println(e);
// }
}
The whole e.printStackTrace:
java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:1062)
at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3556)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2513)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2283)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:822)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at App.conexion.getConnection(conexion.java:93)
at App.conexion.btnConectarActionPerformed(conexion.java:70)
at App.conexion.access$000(conexion.java:19)
at App.conexion$1.actionPerformed(conexion.java:45)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.lang.ClassCastException: java.math.BigInteger cannot be cast
to java.lang.Long
at
com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:1007)
... 54 more
I finally made it thanks to Cirille Con Morales,thanks a lot for the link and the download instruction. My Netbeans has an old installation of MySql connector driver (5.xxx) I downloaded the (8.0.17) version, added to the global libraries and I hed other issues but digging in google I resolve them, this pats must be changed:
I used the driver has an string url :
public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
Then an error abour timezine appeared, so to fix this the URL should be modified whith this:
public static final String URL =
"jdbc:mysql://localhost:3306/escuela?
useUnicode=true&useJDBCCompliantTimezoneShift
=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
Then I used it like this:
public static Connection getConnection(){
Connection con = null;
try{
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
JOptionPane.showMessageDialog(null, "Conexion exitosa.");
}
catch(Exception e){
e.printStackTrace();
}
return con;
}
Regards!

Connect Java fx application to remotely hosted database

I have a remotely hosted database. I had been working on an FX application for which I connected to localhost for reading and writing data from database. But now I want to connect my desktop application to the remotely hosted database and read and write data from there. But it shows me the following error.
SEVERE: null
java.sql.SQLException: null, message from server: "Host '103.253.39.4' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1037)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2239)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2270)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2069)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:794)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:389)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at com.garciaPlumbing.model.DatabaseManager.connect(DatabaseManager.java:38)
at com.garciaPlumbing.model.FittingDetails.getAllSuppliers(FittingDetails.java:155)
at com.garciaPlumbing.view.Layout_AddFittingType.(Layout_AddFittingType.java:52)
at com.garciaPlumbing.view.Layout_InsertFittingDetails.(Layout_InsertFittingDetails.java:37)
at com.garciaPlumbing.view.MenuItemTask.(MenuItemTask.java:23)
at com.garciaPlumbing.view.BasicLayout.(BasicLayout.java:40)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:340)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplicationWithArgs$148(LauncherImpl.java:327)
at com.sun.javafx.application.LauncherImpl$$Lambda$43/445051633.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323)
at com.sun.javafx.application.PlatformImpl$$Lambda$44/1775282465.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/2028529302.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
at com.sun.javafx.application.PlatformImpl$$Lambda$45/2040495657.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1558600329.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "JavaFX Application Thread" Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.NullPointerException
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:358)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:303)
... 5 more
java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:340)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplicationWithArgs$148(LauncherImpl.java:327)
at com.sun.javafx.application.LauncherImpl$$Lambda$43/445051633.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323)
at com.sun.javafx.application.PlatformImpl$$Lambda$44/1775282465.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/2028529302.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
at com.sun.javafx.application.PlatformImpl$$Lambda$45/2040495657.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1558600329.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at com.garciaPlumbing.model.FittingDetails.getAllSuppliers(FittingDetails.java:171)
at com.garciaPlumbing.view.Layout_AddFittingType.(Layout_AddFittingType.java:52)
at com.garciaPlumbing.view.Layout_InsertFittingDetails.(Layout_InsertFittingDetails.java:37)
at com.garciaPlumbing.view.MenuItemTask.(MenuItemTask.java:23)
at com.garciaPlumbing.view.BasicLayout.(BasicLayout.java:40)
... 16 more
This what I have done to establish the connection.
public class DatabaseManager {
private static final String CLASS_FORNAME = "com.mysql.jdbc.Driver";
private static final String DATABASE_LOCATION = "jdbc:mysql://mysql.2freehosting.com/";//"jdbc:mysql://localhost:3306/";
private static final String DATABASE_NAME = "u821323799_grc?";//"GarciaPlumbing2";
private static final String USERNAME = "u821323799_grc";//"root";
protected static Connection connection = null;
protected static PreparedStatement statement = null;
/**
*
* Connect() method is responsible for establishing any connection to database.
*
*/
public static void connect(){
try {
Class.forName(CLASS_FORNAME);
connection = (Connection) DriverManager.getConnection(
"jdbc:mysql://mysql.2freehosting.com/u821323799_grc?"
+ "user=u821323799_grc&password=celloviii1");
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DatabaseManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Please someone help me out with a better solution.
Thanks in advance.
java.sql.SQLException: null, message from server: "Host
'103.253.39.4' is not allowed to connect to this MySQL server"
It means that the MySQL Server at the remote system is not configured to accept remote connection from 103.253.39.4 with the provided credentials. Please configure the remote MySQL Server to accept remote connection and try again.
You may try: How to allow remote connection to mysql

Hive StorageHandler throws exception "Configuration and input path are inconsistent"

I have a HiveStorageHandler if I do select * from myTable it returns all the rows in the underlying storage.
When I do something like select col1 from myTable the underlying mapreduce job throws an exception:
java.lang.RuntimeException: Error in configuring object
at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:75)
at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:133)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:413)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:332)
at org.apache.hadoop.mapred.Child$4.run(Child.java:268)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1438)
at org.apache.hadoop.mapred.Child.main(Child.java:262)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:106)
... 9 more
Caused by: java.lang.RuntimeException: Error in configuring object
at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:75)
at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:133)
at org.apache.hadoop.mapred.MapRunner.configure(MapRunner.java:34)
... 14 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:106)
... 17 more
Caused by: java.lang.RuntimeException: Map operator initialization failed
at org.apache.hadoop.hive.ql.exec.ExecMapper.configure(ExecMapper.java:119)
... 22 more
Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: org.apache.hadoop.hive.ql.metadata.HiveException: Configuration and input path are inconsistent
at org.apache.hadoop.hive.ql.exec.MapOperator.setChildren(MapOperator.java:526)
at org.apache.hadoop.hive.ql.exec.ExecMapper.configure(ExecMapper.java:90)
... 22 more
Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: Configuration and input path are inconsistent
at org.apache.hadoop.hive.ql.exec.MapOperator.setChildren(MapOperator.java:520)
... 23 more
2015-02-12 15:45:51,881 INFO org.apache.hadoop.mapred.Task: Runnning cleanup for the task
If I introduce a HiveMetaHook.preCreateTable and set the location to what my input-path on hdfs is then it works. But my path changes dynamically, and I can't constantly update this property:
#Override
public void preCreateTable(Table tbl) throws MetaException {
if (tbl.getSd().getLocation() != null) {
throw new MetaException("LOCATION should be null.");
}
tbl.getSd().setLocation(*hard-coded-input-path*);
}
I did this based on the following posting.
This was happening because I was changing the the mapred.input.dir on the fly to point to a particular file on hdfs. Now, once i'm finished with own calculations, I set the mapred.input.dir back to what hive had set it to.
I have my own Split for this InputFormat. So every-time FileSplit.getPath() is invoked I return what hive expects which is the original mapred.input.dir and now everything works.
class MySplit extends org.apache.hadoop.mapred.FileSplit {
public MySplit(InputSplit actualSplit, String hiveInputPath) {
super (new Path(hiveInputPath), 0,0, (String[]) null);
this.actualSplit = actualSplit;
}
//do not override getPath that way hiveInputPath is returned
InputSplit getActualSplit() {
return actualSplit;
}
....
}

How to connect JAVA to SQL Server 2012?

Hey friends I am totally new in JAVA and i want to now how to connect JDBC with SQL Server 2012. I go through so much material but i didn't get it. So can you give me a sample demo code...
I have one more problem that i installed SQL Server 2012 but i don't know what is username, password and server name. SO what can i do for it??
When i code it gives error...
Code:
import java.sql.*;
public class Conection
{
public static void main(String a[]) throws ClassNotFoundException, SQLException
{
try
{
String url = "jdbc:sqlserver://localhost:1433//SQLEXPRESS;databaseName=mydb";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
System.out.println("connection created");
Statement st=conn.createStatement();
String sql="select * from mydb";
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
System.out.println("Name: "+rs.getString(1));
//System.out.println("Address : "+rs.getString(2));
}
if(st!=null)
st.close();
if(conn!=null)
conn.close();
}
catch(SQLException sqle)
{
System.out.println("Sql exception "+sqle);
}
}
}
Error
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Conection.main(Conection.java:11)
It seems your sql driver classes is not in classpath. if your are using an IDE add it to classpath else add it manually before compiling your class.

Error in login our application...!

Hello friends i am trying to create a login web page application check out this code it will show an error like this...
.
java.sql.SQLException: No data found
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(Unknown Source)
at LoginServlet.doPost(LoginServlet.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:108)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:379)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcesso
r.java:282)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.pr
ocess(Http11AprProtocol.java:357)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoin
t.java:1687)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source
)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception caught
Code goes here..........
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class LoginServlet extends HttpServlet
{
Connection con;
public void doPost(HttpServletRequest hreq,HttpServletResponse hres) throws ServletException,IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:mohit","system","rock");
PreparedStatement ps=con.prepareStatement("select pswd from signup where username=?");
ps.setString(1,hreq.getParameter("t1"));
ResultSet rs=ps.executeQuery();
if(rs.next())
{
boolean b=(rs.getString(1)).equals(hreq.getParameter("t2"));
System.out.println(rs.getString(1));
System.out.println(hreq.getParameter("t2"));
System.out.println(b);
if(b)
{
hres.sendRedirect("./success.html");
}
else
{
hres.sendRedirect("./error.html");
}
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Exception caught ");
}
}
}
I think it would be highly beneficial for you if you can remove all the database related code out of your servlet and put it in a simple Java class. In that case you can easily test the code without having the need to compile the servlet and restarting your server everytime to debug.
public class ValidateLogin {
public boolean validate(String username, String pwd) {
...
..
}
You use JDBC-ODBC bridge driver sun.jdbc.odbc.JdbcOdbcDriver .It seems that this driver does not support the second call of getXXX() for the same column and you call rs.getString(1) twice , thus error occurs .You can store the result of rs.getString(1) to a variable and then use this variable to access the value of pswd after that.
You can refer
Why I cannot debug a DatabaseMetaData?
for more information

Categories

Resources