I want to connect my database named aaa via jdbc. I tried using type 1 driver and wrte this quote but the error"[Microsoft][ODBC Driver Manager] Invalid string or buffer length"
type 1 code :
import java.sql.*;
import java.io.*;
class test {
public static void main(String a[]) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("first");
Connection con=DriverManager.getConnection("jdbc:odbc:trial","sa","qwerty");
System.out.println("second");
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Then i tried using type 4 driver and i'm getting a compilation error with the getConnection() method
type 4 code:
import java.sql.*;
import java.io.*;
class t {
public static void main(String arg[]) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("first");
Connectin con= DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databaseName=aaa","sa","qwerty");
System.out.println("second");
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Please can some one help me out with these two problems
In your second example there is a typo: Connectin con=... to Connection con=...!
Related
as 2.0 was like java, now in 3.0, I cannot find my error in this code:
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Main {
public static void main(String[] args){
String hostName = "localhost";
Int portNumber = 16834;
String str = "starttimer\r\n";
try {
#SuppressWarnings("resource")
Socket socket = new Socket(hostName, portNumber);
OutputStreamWriter osw = new <br>OutputStreamWriter(socket.getOutputStream(), "UTF-8");$
send(str, osw);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
static void send(String str, OutputStreamWriter o) throws IOException {
o.write(str, 0, str.length());
o.flush();
}
}
By the way dont worry about where is the data going
Obviously, it's not valid ActionScript code. It is Java. That's why you have syntax error. I suggest reading some required minimum about the ActionScript language to be able at least to distinguish it from other one before trying to implement something.
I am using junit request in jmeter to get the performance result of the scripts. When I run the script it is not giving any error however it is not giving the results.
I am adding the jav source code of junit request and also will provide the output screen.
please check what is the issue as i have added the required plugins and jar into the same
package com.seleniummaster.jmeterjunit;
import static org.junit.Assert.*;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.MarionetteDriver;
public class LoginTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
//use Firefox driver
// driver = new FirefoxDriver();
//use demo.mahara.org site for testing
System.setProperty("webdriver.gecko.driver",
"D:\\Seleniumdriver\\geckodriver.exe");
driver = new MarionetteDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
baseUrl = "http://demo.mahara.org";
//timeout if site page does not load in 30 seconds
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#After
public void tearDown() throws Exception {
//quit the test
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
#Test
public void test() throws InterruptedException {
//navigate to base url
driver.get(baseUrl + "/");
//clear username filed
driver.findElement(By.id("login_login_username")).clear();
//enter user name
driver.findElement(By.id("login_login_username")).sendKeys("student1");
//clear password
driver.findElement(By.id("login_login_password")).clear();
//enter password
driver.findElement(By.id("login_login_password")).sendKeys("Testing1");
//click on submit button
driver.findElement(By.id("login_submit")).click();
//assert the Dashboard link text
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.linkText("Dashboard"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
assertEquals("Dashboard", driver.findElement(By.linkText("Dashboard")).getText());
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
I recently faced the same issue. I checked below two boxes in the Junit Request page on Jmeter UI.
Append assertion errors
Append runtime exception
After this when I executed the test again, I found the error in the "View Results Tree" listener under Response Message field.
Hope this helps.
Please try making all private variables as public. It may happen that JMeter is not able access those.
Also, refer console on JMeter, it should show you errors/exceptions.
I tried creating a custom authenticator with Drill 1.5.0 by creating jar based on below source code and drill configuration. I placed the jar in $DRILLHOME/jars/
drill-override.conf File :
drill.exec: {
cluster-id: "drillbits1",
zk.connect: "host1:2181,host2:2181,host3:2181"
security.user.auth: {
enabled: true,
packages += “myorg.drill.security",
impl: “sso"
}
}
DrillMyUserAuthenticator Class:
package myorg.drill.security;
import myorg.drill.security.SSOFilter;
import myorg.drill.security.SecurityServiceException;
import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.exec.exception.DrillbitStartupException;
import org.apache.drill.exec.rpc.user.security.UserAuthenticationException;
import org.apache.drill.exec.rpc.user.security.UserAuthenticator;
import org.apache.drill.exec.rpc.user.security.UserAuthenticatorTemplate;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
#UserAuthenticatorTemplate(type = “sso")
public class DrillMyUserAuthenticator implements UserAuthenticator {
private String ipAddress;
public void setup(DrillConfig drillConfig) throws DrillbitStartupException {
try {
ipAddress= InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
throw new DrillbitStartupException(e);
}
}
public void authenticate(String userName, String password) throws UserAuthenticationException {
try {
SSOFilter.setSourceAddress(ipAddress);
SSOFilter.authenticate(userName, password);
} catch (SecurityServiceException e) {
e.printStackTrace();
throw new UserAuthenticationException(e.getMessage());
}
}
public void close() throws IOException {
}
}
And I am getting below exception:
exception in thread "main" org.apache.drill.exec.exception.DrillbitStartupException: Failure while initializing values in Drillbit.
at org.apache.drill.exec.server.Drillbit.start(Drillbit.java:277)
at org.apache.drill.exec.server.Drillbit.start(Drillbit.java:261)
at org.apache.drill.exec.server.Drillbit.main(Drillbit.java:257)
Caused by: org.apache.drill.exec.exception.DrillbitStartupException: Failed to find the implementation of 'org.apache.drill.exec.rpc.user.security.UserAuthenticator' for type ’sso'
at org.apache.drill.exec.rpc.user.security.UserAuthenticatorFactory.createAuthenticator(UserAuthenticatorFactory.java:103)
at org.apache.drill.exec.rpc.user.UserServer.(UserServer.java:80)
at org.apache.drill.exec.service.ServiceEngine.(ServiceEngine.java:79)
at org.apache.drill.exec.server.Drillbit.(Drillbit.java:89)
at org.apache.drill.exec.server.Drillbit.start(Drillbit.java:275)
Please let me know if I am missing something with the config or code.
I followed Drill's documentation to create this.
Turns out be a documentation issue on Drill Side. https://issues.apache.org/jira/browse/DRILL-4461
Above Jira has the solution to the problem.New jar for the custom authenticator should be created with drill-module.conf in order for the classpath scanner to pick it up
drill: {
classpath.scanning: {
packages: [
"myorg.drill.security"
]
}
}
My error!
DBConnection2.java:38: unreported exception java.lang.InstantiationException; must be caught or declared to be thrown
Class.forName("com.mysql.jdbc.Driver").newInstance();
problem: .newInstance();
My code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
import java.util.*;
import java.sql.*;
import java.util.StringTokenizer;
public class DBConnection2 {
String url = "jdbc:mysql://<myserver>/<myDatabase>";
java.sql.Connection con = null;
String query1;
Statement stmt;
public DBConnection2()
{
try
{
//***error here*****
Class.forName("com.mysql.jdbc.Driver").newInstance();
//***error here*****
}
catch(java.lang.ClassNotFoundException e)
{
System.err.println(e.getMessage());
}
try
{
con = java.sql.DriverManager.getConnection(url,"read","read");
stmt = con.createStatement();
}
catch(SQLException ex)
{
System.err.println("SQLException:72 appserver " + ex.getMessage());
}
}
}
The error is exactly what it says it is. A new instance instantiation through reflection needs to be handled (caught or thrown).
That said, you aren't doing anything with the new instance - you aren't assigning it to anything and in this case, it doesn't even need to be called.
Class.forName("com.mysql.jdbc.Driver");
Just that - it will fix the error.
Realize that this still has other problems lurking in the code - one of which is if you have the error of not being able to load it the class, it will print out an error message, but then it will continue on in the next try block and error out again there.
The Solution:
I added this code
Class.forName("com.mysql.jdbc.Driver");
brfore
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
Thank you all for reply my question
====================
I have problem, I try to insert data into mysql db using servlet, but I couldn'y access to MySQL
Database name: test
Table name: test
I already added jdbc connector to the project library
I'm using JDK 1.7, NetBeans 7.3, MySQL 5.6, Tomcat 7.0, Connector/J 5.1.24
1- this is "form action" in sign_up.jsp page:
<form action="RegisterUser" method="post">
<td><input type="submit" value="Submit"></td>
</form>
2- this is RegisterUser.java servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/RegisterUser"})
public class RegisterUser extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan3";
int phone = 123456;
String insert = "INSERT INTO test VALUES ('\" + name + \"', \" + phone + \")";
s.executeUpdate(insert);
s.close();
con.close();
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
3- the exception result:
HTTP Status 500 - Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
type Exception report
message Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.SecurityException: Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
RegisterUser.processRequest(RegisterUser.java:66)
RegisterUser.doPost(RegisterUser.java:173)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.39 logs.
4- But when I use same code but in java file "without servlet or web app" it's working correctly:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static void main(String[] args){
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan4";
int phone = 8985895;
String insert = "INSERT INTO test VALUES ('" + name + "', " + phone + ")";
s.executeUpdate(insert);
s.close();
con.close();
System.out.println("done");
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
}
so what is problem with servlet? Why the code works with java app. but it doesn't work with web app.?
You are getting Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
It means When you are running it from Web Application, JRE could not find Class in the Classpath.
If this code works in your Standalone it means you need to have a JAR file somewhere containing com.mysql.jdbc.Driver class (so called JDBC driver). This JAR needs to be visible in Tomcat. So, I would suggest placing mysql-jdbc.jar at a physical location to /WEB-INF/lib directory of your project.
Alternatively, you can add Third party libraries like JDBC driver here using
Right Click Project Name--> Properties
from your NetBeans IDE
Then restarting Tomcat should work.
Second, you don't need
import com.mysql.jdbc.Driver;
in your Servlet.
David is right and i want to add, you can also install the driver by pasting the jar file in the the installation folder of java.
\Program Files\Java\jre7\lib\ext
Well i dont like mysql very much and always use Mssql with a windows server 2008. This is the code i use for that, i might be your answer since mysql connection works pretty much the same as sql.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName="+database+";user="+user+";password="+password);
First, you should put that into a persistance layer.
1) Ensure that your JDBC driver is in place. Copy it into your classpath, e.g. /WEB-INF/lib directory. Link: MySQL JDBC Driver Download Page
2) Check your connect string: jdbc:mysql://<server>:<port>/<database>, looks like the port is missing. Try jdbc:mysql://127.0.0.1:3306/test