Unhandled SqlException build issue - sqlexception

the issue I encoutered developing a simple web app that retrieves and displays data from a distant database has similar posts about it, but not quite the same, I went through them and I no solution actually helped me, so the issue is the following, when I debug my page, I wait a while and I'm redirected back to my project on Visual Studio with a Dialog Box entitled SqlException was unhandled by user code
the message in it reads:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Une connexion a été établie avec le serveur, mais une erreur s'est ensuite produite pendant la négociation préalable à l'ouverture de session. (provider: TCP Provider, error: 0 - Une connexion existante a dû être fermée par l’hôte distant.)
The general trouble shooting tips didn't help, here is my aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Mail.aspx.cs" Inherits="CCIT_WebApp1.Mail" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 470px">
<table runat="server">
<asp:Repeater ID="repeater" runat="server">
<HeaderTemplate>
<tr class="Header">
<td>Code</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("code") %>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
and this is my backend aspx.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace WebApp1
{
public partial class Mail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cnct = new SqlConnection("Server=x;User"+
"ID=xx;Password=xxxx;Database=xxxx"))
{
cnct.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Code "+
"FROM Societe", cnct))
{
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string code = rdr.GetString(1);
}
}
}
}
}
}

In same cases I test previously SQL query.
Suggest you to run query SELECT Code From Societe on database, to handle orriginal error.
Probobly table or column name typed with mistake, or something same

Original
This is likely your problem:
using (SqlCommand cmd = new SqlCommand("SELECT Code"+
"FROM Societe", cnct))
You need a space between Code and FROM. Should be: SELECT Code From Societe
Second Try
I would suggest wrapping your execution of the data reader in a try/catch block. Debug what's happening on the exception to see if it gives you any more meaningful information. Something like this...
`
DataSet ds = new DataSet();
using (SqlConnection sqlConn = new SqlConnection(sqlConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Code From Societe", sqlConn))
{
try
{
cmd.CommandType = CommandType.Text;
sqlConn.Open();
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(ds);
}
catch (Exception ex)
{
**Do something here **
}
}
}`

Related

I have my data inside a SqlDataReader and i passed it to the html View, how can i work with that info inside the view, and display it into a table?

I'm developing a scholl project(using asp.net core Web Application) and i select data from a sql server database using a stored procedure into a SqlDataReader, that returns that The return of the stored procedure.
I already passed that SQLDataReader to my html View, now i need to display that data into a html table like this:Table edited in paint to get the desired result, I'm not getting the result I want because i can't work correctly with the data.
That's how i execute the stored Procedure.
SqlCommand cmd = new SqlCommand("tentativa1", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#tempo", "day"));
cmd.Parameters.Add(new SqlParameter("#ap_id", "18"));
SqlDataReader rdr = cmd.ExecuteReader();
That's the code i use to pass the SqlDataReader to the view:
public class MyViewModel
{
public List<teste> objteste { get; set; }
public SqlDataReader rdr { get; set; }
public List<L_AccessPoint> objAcessPoint { get; set; }
}
And thats the code i use to "catch" the data that i pass to the view:
#model MyViewModel
I dont know if use a SqlDataReader is the best way to work with data or if is better use other thing.
If you could help me displaying the desired result, I will be very grateful.
It seems you want use SqlDataReader in razor page directly. Like below
#model MyViewModel
...
// This way is wrong.
Model.rdr
As we know, we can get datas from SqlDataReader, and the datas should be filled in DataSet or DataTable.
So my suggestion is you can refer my sqlheler to get datatable data by query or StoredProcedure.
Then you will get a DataTable in your Method, I have mocked some data same as you provided.
Please check the sentence in the image.
Because the effect displayed on your front-end page still needs to be calculated, I recommend that you create a new DataTable, and then adjust the data according to the business, and then pass the DataTable to the front-end. This is a better way to implement it.
//MyViewModel model = new MyViewModel();
//model.DataObj= ToListByDataTable<DataModel>(dtSource);
DataTable dtYear = new DataTable();
DataView dvYear = dtSource.DefaultView;
dtYear = dvYear.ToTable(true,"year");
DataTable dtShow = new DataTable();
dtShow.Columns.Add("Ap_Name", typeof(String));
for (int i = 0; i < dtYear.Rows.Count; i++)
{
dtShow.Columns.Add(dtYear.Rows[i]["year"].ToString(), typeof(String));
}
// Fill data into the DataTable of dtShow according to certain rules.
return View(dtShow);
Your cshtml should like below:
#using System.Data
#model List<DataTable>
<style>
table, th, td {
border: 1px solid;
}
</style>
<table cellpadding="0" cellspacing="0">
<tr>
<th>Ap_Name</th>
#foreach (DataRow row in Model[0].Rows)
{
<th>#row["year"]</th>
}
</tr>
#foreach (DataRow row in Model[1].Rows)
{
<tr>
<td>#row["Ap_Name"]</td>
#foreach (DataRow row1 in Model[0].Rows) {
<td>#row1["year"]</td>
}
</tr>
}
</table>
You need fill in data by yourself.

Please I was trying to connect my project to a database but i got an error: the name ‘textbox’ does not exist in the current context

This is my aspx.cs code for the connection which I tried to use and it gave me the error
using System.Data.SqlClient;
public partial class index : System.Web.UI.Page
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ("Data Source=.SQLEXPRESS;AttachDbFilename=C:Users SOLO Desktop DesHomeWeb App_Data Database.mdf;Integrated Security=True;Encrypt=False;User Instance=True");
con.Open();
}
protected void btn3_click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into signup " + " (fname)values(#fname)", con);
cmd.Parameters.AddWithValue("#fname", textbox.text);
}
}
This is the HTML code for the textbox in my aspx codding window
<td><input type="text" placeholder="First Name" class="textbox1" id="textbox" /></td>
In ASP.NET web forms, I believe that you will need to use the asp:TextBox control rather than the html input element as shown below:
<form id="form1" runat="server">
<asp:TextBox placeholder="First Name" ID="textbox" runat="server" CssClass="textbox1"></asp:TextBox>
<asp:Button id="btn3" Text="Sign Up" OnClick="btn3_click" runat="server"/>
</form>
Assuming that your SQL Server Express database is named "Database.mdf" and it is located in the App_Data folder of your solution, you can use the |DataDirectory| variable instead of the physical path to your database file. ASP.NET will automatically substitute the file path to the App_Data directory for the |DataDirectory| variable when it opens the connection to the database. Note, that you will need to escape the backslash character by using double backslash \ in your connection string:
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;Encrypt=False;User Instance=True";

Error: No suitable driver found for jdbc:mysql://localhost:3306/wt

I know I am not supposed to use this code on JSP, but I just wanna check the connectivity to the database. So I am using this to check with a JSP page. But when I checked it, it threw me an error like this:
Error: No suitable driver found for jdbc:mysql://localhost:3306/wt
Source code of database.jsp:
<section>
<h3><code>Users</code> Table</h3>
<%
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/wt";
String user = "root";
String password = "";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println("Error: " + ex.getMessage());
}
%>
</section>
I have also included mysql-connector-java-5.1.34-bin.jar to the list of libraries. I am using the following stack:
MySQL 5.6.17
Eclipse Luna (J2EE Perspective)
JBoss 6.1 Distribution Server
Please guide me where I am going wrong. Thanks in advance.
Load the class:
Class.forName(mysqlDriverClass).newInstance();
Before you invoke any jdbc methods?
UPDATE
Include the SQL JSTL class using <%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> and set your datasource <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/TEST" user="root" password="pass123"/> to whatever you need. Be sure to include the jstl jar.

HTTP Status 500 - An exception occurred processing JSP page /webtech/login.jsp at line 6

Its basicaly a simple project to check login and password...
i did all the things possible to figure out the error...but i cannot somehow get over it...can anyone please help and provide solution for me.
i have a html file name Login.html and a jsp file named login.jsp
mysql port no. is 3306 with username and password sait
my tomcat port no. is 8801.
Login.html
<html>
<head></head>
<body>
<form action="login.jsp" method="post">
User name :<input type="text" name="usr" />
password :<input type="password" name="pwd" />
<input type="submit" />
</form>
</body>
</html>
login.jsp
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String userid=request.getParameter("usr");
String pswd=request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sait","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from login where username='"+userid+"'");
if(rs.next())
{
if(rs.getString("password").equals(pswd))
{
out.println("welcome"+userid);
}
else
{
out.println("Invalid password try again");
}
}
%>
i created a folder in C:\program files\apache software foundation\tomcat 7.0\webapps\ROOT\webtech**
and placed this 2 files **\webetech\Login.html and \webtech\login.jsp
i opened mysql and created a database named "sait"..then changed the database to "sait" using the command "use sait;" in mysql.
then i executed the following code
mysql>create table login(username varchar(10),password varchar(10));
>insert into login values("sait","sait");
>select * from login;
all executed successfully..
then i placed mysql-connector-java-5.1.26-bin in d destination C:\program files\apache software foundation\tomcat 7.0\lib\mysql-connector-java-5.1.26-bin.jar
now if i go to
http://localhost:8081/webtech/Login.html
i get the login page..but after i submit i get HTTP Status 500 - An exception occurred processing JSP page /webtech/login.jsp at line 6
Plssss help
I guess you might get NullpointerException . so just print the values of
String userid=request.getParameter("usr");
String pswd=request.getParameter("pwd");
out.print(userid + "" + pswd);
and check it out . Also its highly discourged to use the java codes in jsp pages . try using a servlet to establish JDBC
You should also add try/catch block your code to catch any exception if thrown ,
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String userid=request.getParameter("usr");
String pswd=request.getParameter("pwd");
out.print(userid + "" + pswd);
try
{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sait","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from login where username='"+userid+"'");
while(rs.next())
{
if(rs.getString("password").equals(pswd))
{
out.println("welcome"+userid);
}
else
{
out.println("Invalid password try again");
}
}}
catch(Exception e)
{
out.print("Exception is " + e);
}
%>
If this didnt solve your issue . please post us the exception you are getting
Hope this helps !!

Access2007 OleDbConnection over network share persists although share is deletedH

I've encountered a quite strange behavior of ADO.NET / Access 2007.
I run my C# 2008 program (target framework .NET 2.0) on PC1.
PC1 has a network share on PC2 (\PC2\Temp mapped as X:)
On PC2 in Temp there is the access database file xy.mdb
The program opens a OleDbConnection to X:\xy.mdb. Works fine.
Then while the program is still running I drop the share on PC2.
(Windows Explorer on PC1 tells me the share X: is lost)
I renamed the database file on PC2, so no new connection should be possible.
But the program can still query the database !
(via OleDbCommand.ExecuteReader() or ExecuteNonQuery())
Has anyone an explanation for me ?
Is the whole database latched ?
And can I prevent this so that I get an OleDbException when the share is dropped and I try to query the no longer available database ?
Thanks for any help,
Ralf
I tried to reproduce the issue with the following code and a sample access db...not matter how I tried (sahre or mapped drive) i always got the exception:
Unhandled Exception:
System.Data.OleDb.OleDbException: The
Microsoft Jet database engine cannot
find the input table or query
'somejunk'. Make sure it exists and
that its name is spelled correctly.
which is expected. You should re-examine you environment to be 100%.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
namespace AccessOverShare
{
class Program
{
static void Main(string[] args)
{
int ct = 0;
using(OleDbConnection oleDbConnection = new OleDbConnection())
{
//oleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\127.0.0.1\\share\\test.mdb.";
oleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\\test.mdb.";
oleDbConnection.Open();
using(OleDbCommand oleDbCommand = oleDbConnection.CreateCommand())
{
oleDbCommand.CommandType = CommandType.Text;
oleDbCommand.CommandText = "select junkid, junktext from somejunk";
using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader(CommandBehavior.Default))
{
ct = 0;
while(oleDbDataReader.Read())
{
ct++;
Console.WriteLine("{0:0000}", oleDbDataReader["junkid"]);
}
}
Console.WriteLine();
Console.WriteLine(ct);
}
Console.WriteLine();
Console.WriteLine();
Console.Write("kill the share then press enter to continue");
Console.ReadLine();
using (OleDbCommand oleDbCommand = oleDbConnection.CreateCommand())
{
oleDbCommand.CommandType = CommandType.Text;
oleDbCommand.CommandText = "select junkid, junktext from somejunk";
using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader(CommandBehavior.Default))
{
ct = 0;
while (oleDbDataReader.Read())
{
ct++;
Console.WriteLine("{0:0000}", oleDbDataReader["junkid"]);
}
}
Console.WriteLine();
Console.WriteLine(ct);
}
}
}
}
}