This is code cut right from the Dapper examples:
var p = new DynamicParameters();
p.Add("#a", 11);
p.Add("#b", dbType: DbType.Int32, direction: ParameterDirection.Output);
p.Add("#c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
cnn.Execute("spMagicProc", p, commandType: commandType.StoredProcedure);
int b = p.Get("#b");
int c = p.Get("#c");
Anyone: In the above code from the example provided, I get an error, "can't resolve .Execute"--referring to cnn.Execute. I look at the connection object and there is no method for Execute. Dapper obviously works well, so what am I doing wrong?
I believe this should get you fixed up:
using( var connection = new SqlConnection( connectionString ) )
{
try
{
var p = new DynamicParameters();
p.Add( "a", 11 );
p.Add( "b", dbType: DbType.Int32, direction: ParameterDirection.Output );
p.Add( "c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue );
connection.Open();
connection.Execute( "MyDamnStoredProc", p, commandType: CommandType.StoredProcedure );
int b = p.Get<int>( "b" );
int c = p.Get<int>( "c" );
}
catch( Exception ex )
{
Console.WriteLine( ex.Message );
}
}
Notes:
the params don't need the # symbol; dapper will handle that for you.
be sure to use named parameters; see the updated connection.Execute method that specifies the commandType: parameter. You do this so the optional parameters can be omitted from the method call.
"can't resolve .Execute"
That would be cause your extension method is missing, did you using Dapper; at the top of your file.
See also: http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic3
Related
I am trying to view data from the SQL Server and I have a column (note) that accept null value because it is not necessary for the user to input any values. I tried using the "rs.wasNull" method as below:
var Note : String = rs.getString("note")
if(rs.wasNull()){
Note = ""
}
But I have still facing the error saying that the "rs.getString("note) cannot be null. Is there any possible ways to return null value?
Below are my whole code:
private fun displayData() {
val sqlCon = SQLCon()
connection = sqlCon.connectionClass()!!
var cUser : String? = intent.getStringExtra("Current User")
if (connection == null) {
Toast.makeText(this, "Failed to make connection", Toast.LENGTH_LONG).show()
} else {
try {
val sql : String=
"SELECT * FROM Goals where Username = '$cUser' "
statement = connection!!.createStatement()
var rs : ResultSet = statement!!.executeQuery(sql)
while (rs.next())
{
var Note : String = rs.getString("note")
if(rs.wasNull()){
Note = ""
}
gList.add(GoalList(rs.getString("gName"), rs.getDouble("tAmount"), rs.getDouble("sAmount"), rs.getString("note"), rs.getString("date")))
}
rs.close()
statement!!.close()
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show()
} catch (e: Exception) { Log.e("Error", e.message!!) }
}
}
You use non-nullable return type for note variable:
var Note : String = rs.getString("note")
First, the variable name should start with a lowercase letter -> note.
Secondly, return value must be nullable
var note : String? = rs.getString("note")
In accordance with JavaDoc getString function:
Returns: the column value; if the value is SQL NULL, the value
returned is null
So no need to check if it was null or not, you can use the following construction to pass default value:
var note : String = rs.getString("note") ?: ""
I am new to .NET Core. I have defined the connection string in appsettings.json like this:
"ConnectionStrings": {
"TestBD": "Server=localhost;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
}
I am not using Entity Framework. I need to connect to the database using this connection string from the Program.cs file.
Any help is really appreciated. Thanks
You refer the following sample code to use ADO.NET in Asp.net 6 program.cs:
//required using Microsoft.Data.SqlClient;
app.MapGet("/movies", () =>
{
var movies = new List<Movie>();
//to get the connection string
var _config = app.Services.GetRequiredService<IConfiguration>();
var connectionstring = _config.GetConnectionString("DefaultConnection");
//build the sqlconnection and execute the sql command
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
string commandtext = "select MovieId, Title, Genre from Movie";
SqlCommand cmd = new SqlCommand(commandtext, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var movie = new Movie()
{
MovieId = Convert.ToInt32(reader["MovieId"]),
Title = reader["Title"].ToString(),
Genre = reader["Genre"].ToString()
};
movies.Add(movie);
}
}
return movies;
});
The result like this:
In this example I use Npgsql in development version 3.1.0-alpha6.
I want to specify a PostgisGeometry object as a parameter in a query (NpgsqlDbType.Geometry)
and select the object again.
Queries with types like Point, MultiPoint, LineString, MultiLineString, Polygon and GeometryCollection will be returned correctly. A PostgisMultiPolygon object with only one polygon will be returned correctly too.
However, it does not work with a PostgisMultiPolygon with more than one polygon.
PostgisMultiPolygon geom1 = new PostgisMultiPolygon(new[]
{
new PostgisPolygon(new[]
{
new[]
{
new Coordinate2D(40, 40),
new Coordinate2D(20, 45),
new Coordinate2D(45, 30),
new Coordinate2D(40, 40)
}
})
}) {SRID = 4326};
PostgisMultiPolygon geom2 = new PostgisMultiPolygon(new[]
{
new PostgisPolygon(new[]
{
new[]
{
new Coordinate2D(40, 40),
new Coordinate2D(20, 45),
new Coordinate2D(45, 30),
new Coordinate2D(40, 40)
}
}),
new PostgisPolygon(new[]
{
new[]
{
new Coordinate2D(20, 35),
new Coordinate2D(10, 30),
new Coordinate2D(10, 10),
new Coordinate2D(30, 5),
new Coordinate2D(45, 20),
new Coordinate2D(20, 35)
}
})
}) {SRID = 4326};
using (NpgsqlConnection connection = CreateConnection())
{
NpgsqlCommand command = connection.CreateCommand();
command.Parameters.AddWithValue("p1", NpgsqlDbType.Geometry, geom1);
command.CommandText = "Select :p1";
command.ExecuteScalar();
}
using (NpgsqlConnection connection = CreateConnection())
{
NpgsqlCommand command = connection.CreateCommand();
command.Parameters.AddWithValue("p1", NpgsqlDbType.Geometry, geom2);
command.CommandText = "Select :p1";
command.ExecuteScalar(); //timeout occurs...
}
If increasing the CommandTimeout, the timeout occurs anyway.
Thanks in advance!
The fix for this bug has just been merged: https://github.com/npgsql/npgsql/pull/1025
I am attempting to define a variable conn in my controller.js.
With the code at the bottom, I get lots of horrible UI glitches, so I'm presuming the code below is wrong. If I try:
var conn;
conn.name = 'Fred';
I get what looks like a NullPointer Error "Cannot set property 'name' of undefined" when I attempt to set conn.name.
How do I define my variable?
var addDBConnControllerBase = app.controller('addDBConnControllerBase',
function($scope,$http,serviceFactory,$modal,$location,$log)
{
$scope.saveDBConn = function()
{
var conn = {
name,
driverType,
connectionString,
userID,
password
};
conn.name = $scope.addDBConnController.displayName;
conn.driverType = $scope.addDBConnController.driverType;
conn.connectionString = $scope.addDBConnController.connectionString;
conn.userID = $scope.addDBConnController.userID;
conn.password = $scope.addDBConnController.password;
$log.debug('Saving db conn');
$log.debug(JSON.stringify(conn));
}
});
var newAttrs = {};
newAttrs[nameOfProp] = valueOfProp;
try this!!!
In your case I think this would be
var conn = {};
conn["name"] = 'Fred';
You need to brush up on your javascript pronto! This:
var conn;
is a variable declaration, not definition. conn is still undefined after this statement so you can't go conn.name = .... You have to initialize things before you use them:
var conn = {};
conn.name = ...
or
var conn = {
name: ...
};
You should define variable conn as an array first. Like following.
var conn = [];
conn.name=$scope.addDBConnController.displayName;
Here's my code:
var sb = new qx.ui.form.SelectBox();
sb.add( new qx.ui.form.ListItem("English") );
sb.add( new qx.ui.form.ListItem("Nederlands") );
sb.add( new qx.ui.form.ListItem("Deutsch") );
sb.add( new qx.ui.form.ListItem("français") );
sb.add( new qx.ui.form.ListItem("Српски") );
How do I use setSelection() to select "Deutsch", and what if the items are numeric values? Can I also set values for these labels or is SelectBox() limited to labels?
For example:
value: en, label: English
value: de, label: Deutsch
etc.
Take a look at the example code below.
You can specify a model with each ListItem for storing additional information. It can act as value property on form items for example. See http://demo.qooxdoo.org/1.0.x/apiviewer/#qx.ui.form.ListItem
var selectBox = new qx.ui.form.SelectBox();
selectBox.add( new qx.ui.form.ListItem("English", null, "en" ));
selectBox.add( new qx.ui.form.ListItem("Nederlands", null, "nl" ));
var defaultItem = new qx.ui.form.ListItem("Deutsch", null, "de" );
selectBox.add(defaultItem );
selectBox.add( new qx.ui.form.ListItem("français", null, "fr"));
selectBox.add( new qx.ui.form.ListItem("Српски", null, "ru"));
selectBox.setSelection([defaultItem]);
selectBox.addListener("changeSelection", function(e) {
//Read model data from listitem
this.debug("changeSelection: " + e.getData()[0].getModel());
});
Maybe this example will be useful for you too:
var sb = new qx.ui.form.SelectBox();
var a = ["English", "Nederlands", "Deutsch", "Français", "Српски"];
var model = new qx.data.Array(a);
var controller = new qx.data.controller.List(model, sb);
controller.setSelection(model.slice(0,3));
At last line model.slice(0,3) returns subarray of model with three elements: from "English" to "Deutsch". And last element in this subarray will be "selected" by default.
See "Data Binding" in qooxdoo's manual for details.